Hello guys, if you have gone through any coding interview or have done some professional Software development then you know that a good understanding of array data structure is crucial for any software developer but it doesn't come for free, you need to spend time and effort. The best way to develop this understanding by solving coding problems and there are lots of programming exercises beginners can do. One of them is writing a program to find the smallest and largest number in an integer array. Java programmers are no different than others, so they can do this program in Java, not just to understand array but also different relational operators available in Java.
In this program, you need to write a method, yes we call the function a method in Java, which will accept an integer array and then print the largest and smallest number from that array. Use of any third-party library or API method is not allowed, which means you need to do this exercise by using essential tools of Java programming language, which includes operators, control statements, keywords, and some classes from java.lang package.
This problem is also known as finding maximum and minimum numbers in an array, and the technique mentioned here can be used in any other programming language as well. As a bonus point, you can also write JUnit test cases to test your method, I have not done so and relied on a simple main method to test my code to show the output and keep it short, essential for any example or demo.
Btw, if you preparing for a programming job interview, then let me repeat that a good knowledge of essential data structures like an array, linked list, binary tree, the hash table goes a long way in doing well on the interview. You should spend some time learning those and filling gaps in your understanding.
Here is a full code example of a Java program to find the smallest and largest number from an integer array. You can create a Java source file with the name MaximumMinimumArrayDemo.java and copy code there to compile and execute it in your favorite IDE.
In this program, you need to write a method, yes we call the function a method in Java, which will accept an integer array and then print the largest and smallest number from that array. Use of any third-party library or API method is not allowed, which means you need to do this exercise by using essential tools of Java programming language, which includes operators, control statements, keywords, and some classes from java.lang package.
This problem is also known as finding maximum and minimum numbers in an array, and the technique mentioned here can be used in any other programming language as well. As a bonus point, you can also write JUnit test cases to test your method, I have not done so and relied on a simple main method to test my code to show the output and keep it short, essential for any example or demo.
Btw, if you preparing for a programming job interview, then let me repeat that a good knowledge of essential data structures like an array, linked list, binary tree, the hash table goes a long way in doing well on the interview. You should spend some time learning those and filling gaps in your understanding.
Java Program to find the smallest and largest number in an integer array
If you don't have an IDE setup, you can also compile and run this program by following the steps I have shown on HelloWorld in Java.
If you look at the code here, we have created a method called the largestAndSmallest(int[] numbers) to print the largest and smallest number from the int array passed to the program. We have used two variables largest and smallest, to store the maximum and minimum values from the array.
If you look at the code here, we have created a method called the largestAndSmallest(int[] numbers) to print the largest and smallest number from the int array passed to the program. We have used two variables largest and smallest, to store the maximum and minimum values from the array.
Initially, the largest is initialized with Integer.MIN_VALUE and smallest are initialized with Integer.MAX_VALUE.In each iteration of the loop, we compare the current number with the largest and smallest and update them accordingly.
Since if a number is larger than the largest, it can't be smaller than the smallest, which means you don't need to check if the first condition is true, that's why we have used if-else code block, where else part will only execute if the first condition is not true.
Here is another logical diagram or flow chart to find the largest element from an array in Java, here instead of assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.
Since the array doesn't override the toString method in Java, we have used Arrays.toString() to print the contents of an array. Remember, this function is outside of core logic, so it's ok to use it. Since this is a static method, we can directly call this from the main method in Java, and so does our test code.
We pass the random array to this method and see if the largest and smallest number returned by the method is correct or not. For automated testing, a Unit test is better, but for a demonstration, you can use the main method.
Btw, if you preparing for a programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 189 Programming Questions and Solutions, which is more than enough for many coding interviews.
That's all about How to find the largest and smallest number from integer array in Java. As I said, this question can also be asked to find the maximum and minimum numbers in an Array in Java, so don't get confused there. By the way, there are more ways to do the same task, and you can practice it to code solutions differently. Can you write a solution that is different than this? Go ahead and give it a try.
Here is another logical diagram or flow chart to find the largest element from an array in Java, here instead of assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.
Since the array doesn't override the toString method in Java, we have used Arrays.toString() to print the contents of an array. Remember, this function is outside of core logic, so it's ok to use it. Since this is a static method, we can directly call this from the main method in Java, and so does our test code.
We pass the random array to this method and see if the largest and smallest number returned by the method is correct or not. For automated testing, a Unit test is better, but for a demonstration, you can use the main method.
Btw, if you preparing for a programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 189 Programming Questions and Solutions, which is more than enough for many coding interviews.
Java Program to find the largest and smallest element in an array:
Here is the Java program I am talking about. This shows you how to find the maximum and minimum number in a given array in Java, without using any library method.import java.util.Arrays; /** * Java program to find largest and smallest number from an array in Java. * You cannot use any library method both from Java and third-party library. * * @author http://java67.com */ public class MaximumMinimumArrayDemo{ public static void main(String args[]) { largestAndSmallest(new int[]{-20, 34, 21, -87, 92, Integer.MAX_VALUE}); largestAndSmallest(new int[]{10, Integer.MIN_VALUE, -2}); largestAndSmallest(new int[]{Integer.MAX_VALUE, 40, Integer.MAX_VALUE}); largestAndSmallest(new int[]{1, -1, 0}); } public static void largestAndSmallest(int[] numbers) { int largest = Integer.MIN_VALUE; int smallest = Integer.MAX_VALUE; for (int number : numbers) { if (number > largest) { largest = number; } else if (number < smallest) { smallest = number; } } System.out.println("Given integer array : " + Arrays.toString(numbers)); System.out.println("Largest number in array is : " + largest); System.out.println("Smallest number in array is : " + smallest); } } Output: Given integer array : [-20, 34, 21, -87, 92, 2147483647] Largest number in array is : 2147483647 Smallest number in array is : -87 Given integer array : [10, -2147483648, -2] Largest number in array is : 10 Smallest number in array is : -2147483648 Given integer array : [2147483647, 40, 2147483647] Largest number in array is : 2147483647 Smallest number in array is : 40 Given integer array : [1, -1, 0] Largest number in array is : 1 Smallest number in array is : -1
That's all about How to find the largest and smallest number from integer array in Java. As I said, this question can also be asked to find the maximum and minimum numbers in an Array in Java, so don't get confused there. By the way, there are more ways to do the same task, and you can practice it to code solutions differently. Can you write a solution that is different than this? Go ahead and give it a try.
Some more programs for coding interviews:
- How to check if a given number is prime or not? (solution)
- 10 Free Courses to learn Data Structure and Algorithms (courses)
- How to find the highest occurring word from a text file in Java? (solution)
- 100+ Data Structure and Algorithms Problems (solved)
- 10 Books to learn Data Structure and Algorithms (books)
- How to find if given String is a palindrome in Java? (solution)
- How to reverse an int variable in Java? (solution)
- How do you swap two integers without using the temporary variable? (solution)
- Write a program to check if a number is a power of two or not? (solution)
- How to reverse String in Java without using StringBuffer? (solution)
- How do you reverse the word of a sentence in Java? (solution)
- 10 Data Structure and Algorithms course to crack coding interview (courses)
- How to find a missing number in a sorted array? (solution)
- How to find the square root of a number in Java? (solution)
- How to calculate the GCD of two numbers in Java? (solution)
- How to find duplicate characters from a given String? (solution)
- Top 10 Programming problems from Java Interviews? (article)
hard???
ReplyDeletepackage Sankey;
Deletepublic class smalestno
{public static void main(String[] args) {
int a[]={-12,-1,-13,22,54,65,4,7,9,5,765,765567};
int n=0;
n=a.length-1;
//System.out.println(n);
for(int i=0;ia[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("smallest " +a[0]);
System.out.println("largest "+a[n]);
}
}
this can easily done with python.
Deleteimport array as arr
x=arr.array("i",[2,3,4,5,543,556])
print(max(x))
print(min(x))
output:
556
2
This code doesn't look right, it should be changed to (remove "else"):
ReplyDeleteif (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
If you try {1, 2, 3}, you will see the difference.
Agreed. I ran the code example and encountered the incorrect result. It should be updated to have two separate if statements just as shown above.
DeleteWhy not just set largest/smallest to array[0] instead of INT_MAX, INT_MIN? Then it'll work with the `else`. Setting to INT_MAX/INT_MIN is a rather rookie mistake.
Deletewhen smallest is the first element if does not give the right answer so there should be two if statements in place of if else if.
Deleteyes.
DeleteRemove "else" because it fails at both places.
ReplyDelete1. for largest try ascending order digit (1,2,3)
2. for smallest try descending order digit in negative(-3,-2,-1)
Yes, the else looks like a typo, it should be removed otherwise solution will not produce correct result for all outputs.
Delete//programm to find largest no in an given array.
ReplyDeletepublic class Larg {
public static void main(String[] args) {
int max=0;
int arr[]={900,2,54,15,40,100,20,011,299,30,499,699,66,77};
max=arr[0];
for(int i=0;i<arr.length-1;i++)
{
if(max<arr[i+1])
{
max=arr[i+1];
}
}
System.out.println(max);
}
}
super.....
Deletenice article
ReplyDeleteCan we convert into array into string without API or without Arrays.to String(arr)
ReplyDeleteCan we convert int array to string without using Arrays.to string()
ReplyDeleteyes bro u can do it.
Deleteprivate static void largestAndSmallest(int[] numbers) {
ReplyDeleteint largest = numbers[0];
int smallest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if(numbers[i]>largest){
largest=numbers[i];
}else if(numbers[i]<smallest){
smallest=numbers[i];
}
}
System.out.println("\nGiven integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}
ReplyDeleteimport java.util.Scanner;
class exam
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter 5 numbers:");
int[] numbers = new int[5];
int sum = 0;
int max = numbers[0];
int min = numbers[0];
for(int i=0; i<5; i++){
numbers[i] = input.nextInt();
sum = sum + numbers[i];
if (numbers[i] > max){
max = numbers[i];
}
else if (numbers[i] < min){
min = numbers[i];
}
}
int average = sum / 5;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + max);
System.out.println("Min: " + min );
System.out.println("Display sorted data : " + numbers[0] );
}
}
How come the min is always displaying 0...Please can someone help me...Thanks in advance
Else in this snippet "else if (numbers[i] < min){" is the culprit
Deletepublic void doAlgorithm(int a[]){
ReplyDeleteint big = 0, temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
big = (a[i] > a[j]) ? a[i] : a[j];
if(temp < big)
temp = big;
}
}
System.out.println(temp);
}
laughable
ReplyDeletewhy all this hassle with Integer.MAX_VALUE and Integer.MIN_VALUE?
Simply make your largest and smallest values equal to the numbers[0]. Then you can save one iteration.
What if the numbers is empty? You will still get Integer.MIN_VALUE and Integer.MAX_VALUE which obviously would be incorrect. You need to check for empty and null array.
A programmer should learn to check his inputs way earlier, than he would learn algorithms. It's a matter of simple hygiene - learn to brush your teeth before learning how to assemble fusion reactor.
int[] arr = {1,3,2,6,3};
ReplyDeleteArrays.sort(arr);
int min = arr[0];
int max = arr[arr.length-1];
System.out.println(min + ":" + max);
Here is the code
ReplyDeleteWhy not you correct code in this post..please replace else if with if condition..
ReplyDeleteint a[]= {10,3,0,1,45,22,667,8,99,0,3};
ReplyDeleteint min = a[0];
int max = a[1];
int minPos = 0;
int maxPos = 1;
if(maxa[i]) {
min = a[i];
minPos = i;
}
if(max<a[i]) {
max = a[i];
maxPos = i;
}
}
System.out.println("min : "+ min +" Pos : "+(minPos+1));
System.out.println("max : "+ max +" Pos : "+(maxPos+1));
import java.util.Arrays;
ReplyDeleteimport java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class Test{
int []arr = {-1 , 3,2, -9, 5 ,6 ,-4};
System.out.println("Largest is "+findLargest(arr));
System.out.println("Smallest is "+findSmallest(arr));
}
private static int findSmallest(int[] arr) {
List b = Arrays.asList(ArrayUtils.toObject(arr));
return (int) Collections.min(b);
}
public static int findLargest(int [] arr){
List b = Arrays.asList(ArrayUtils.toObject(arr));
return (int) Collections.max(b);
}
}
public static void main (String []args){
ReplyDeletelargestAndSmallest(new Integer[]{-20, 34, 21, -87, 92,
10,100,-120});
}
public static void largestAndSmallest(Integer[] numbers)
{
int largest = 0;
int smallest = 0;
int temp = 0;
/*
//// simple using builtin function for sorting array in ascending order ////
Arrays.sort(numbers);
System.out.println("In asscending order : " + Arrays.toString(numbers));
//// simple using builtin function for sorting array in descending order ////
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println("In descending order : " + Arrays.toString(numbers));
*/
for(int i=0; i numbers[j]){
// temp = numbers[i];
// numbers[i]=numbers[j];
// numbers[j]=temp;
// }
// largest = numbers[0];
// smallest = numbers[j];
}
}
System.out.println("Given integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}
import java.util.BitSet;
ReplyDeletepublic class SmallestLargest {
public static void main(String[] args) {
int array[] = new int[] {4,64,3,67,12};
BitSet bitSet = new BitSet();
for(int i = 0; i < array.length; i++) {
bitSet.set(array[i] - 1);
}
System.out.println("Smallest Number is " + (bitSet.nextSetBit(0) + 1));
System.out.println("Largest Number is: " + bitSet.length());
}
}
you can just replace the max and the min with the first element and it works.
ReplyDeletejust use arr[0] in both places
public class FindMaxSmall {
ReplyDeletepublic static void main(String[] args) {
// TODO Auto-generated method stub
int[] arrayValue = { 2, 3, 1, 4, 7, 8, 5, -1, -2, 99, 2, 2, 99 };
int maximum = arrayValue[0];
int minimum = arrayValue[0];
for (int i=1;i maximum) {
maximum = arrayValue[i];
}
if (arrayValue[i] < minimum) {
minimum = arrayValue[i];
}
}
System.out.println("Maximum Value" + maximum);
System.out.println("Minimum Value" + minimum);
}
}
public class MyClass {
ReplyDeletepublic static void main(String args[]) {
int[] array = {2,1,3,4,5,6,7,8,10,9};
int min=array[0];
int max=0;
for(int i=0;iarray[i])
{
min=array[i];
}else if(max<array[i]){
max=array[i];
}
}
System.out.println("Min Number = " + min);
System.out.println("Max Number = " + max);
}
}
Ware is your if condition??
Deletelol
ReplyDeleteint [] array = {3,2,5,1,6};
Arrays.sort(array);
int min = array[0];
int max = array[array.length - 1];
System.out.println("min = " + min + " max = " + max);
static void maxMin(int[] arr){
ReplyDeleteint min = arr[0];
int max = arr[0];
for(int i = 1; i < arr.length;i++){
if(max < arr[i]){
max = arr[i];
}
if(min > arr[i]){
min = arr[i];
}
}
System.out.println(String.format("Max = %s, Min = %s", max, min));
}
Using Binary method:
ReplyDeleteprivate void minAndMax(int[] intArray) {
int middle = intArray.length / 2;
int k = intArray.length - 1;
int minVal = Integer.MIN_VALUE;
int maxVal = Integer.MAX_VALUE;
for (int i = 0; i < middle; i++) {
if(intArray[i] >= minVal){
minVal = intArray[i];
}else if(intArray[i] < maxVal){
maxVal = intArray[i];
}
if(intArray[k] >= minVal){
minVal = intArray[k];
}else if(intArray[k] < maxVal){
maxVal = intArray[k];
}
k--;
}
System.out.println("minVal -->"+minVal);
System.out.println("maxVal -->"+maxVal);
}
private void minAndMax(int[] intArray) {
ReplyDeleteint middle = intArray.length / 2;
int k = intArray.length - 1;
int minVal = Integer.MIN_VALUE;
int maxVal = Integer.MAX_VALUE;
for (int i = 0; i < middle; i++) {
if(intArray[i] >= minVal){
minVal = intArray[i];
}else if(intArray[i] < maxVal){
maxVal = intArray[i];
}
if(intArray[k] >= minVal){
minVal = intArray[k];
}else if(intArray[k] < maxVal){
maxVal = intArray[k];
}
k--;
}
System.out.println("minVal -->"+minVal);
System.out.println("maxVal -->"+maxVal);
}
public static void main(String args[]) {
ReplyDeleteint[] arr = { 5, 2, 3, 41, -95, 530, 6, 42, -361, 81, 8, 19, 90 };
int smallest = arr[0];
int largest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
for (int i = 1; i < arr.length; i++) {
if (smallest >= arr[i]) {
smallest = arr[i];
}
}
System.out.println(largest);
System.out.println(smallest);
}
ReplyDeletevar a = [100, 500, 1000, 5000, 350000, 100000, 200000, 15, 20, 30, 25, 2];
var b = [];
function largestNumber(a){
for(let i=0; i<= a.length-2 ;i++){
// console.log(a[i])
if(i==0){
b.push(a[i])
}
if (i > 0){
if(b[0] <= a[i+1]){
b.pop()
b.push(a[i+1])
}
}
else if(b[0] <= a[i+1]){
b.pop()
b.push(a[i+1])
}
console.log(b +" is bigger number than " + a[i+1])
}
}
largestNumber(a)
console.log(b)
Why not to use mergesort?.. Also,Merge sort time complexity is O(nlogn).. After merge sort, access first and last elements as smallest and largest elements
ReplyDeleteIF sorting is allowed then yes you can use either quicksort or mergesort, but if sorting is not allowed then you need to write a different logic. Also, sorting is overkill because you don't need to sort whole array, you just need to find largest and smallest.
Deleteint min = 0;
ReplyDeleteint max = 0;
int arr[] = {3,2,6,9,1};
for (int i = 0; i < arr.length;i++){
min = arr[0];
if (arr[i] <= min){
min = arr[i];
}else if(arr[i] >= max){
max = arr[i];
}
}
System.out.println(min + " " + max);
int arr[] = {90000000,25145,6221,90000,3213211};
ReplyDeleteint min = arr[0];
int max = arr[0];
for (int i = 0; i < arr.length;i++){
if (min >= arr[i]){
min = arr[i];
}
if(arr[i] >= max){
max = arr[i];
}
}
System.out.println(min + " " + max);
int[] arrays = { 100, 1, 3, 4, 5, 6, 7, 8, 9, 2, 1 };
ReplyDeleteArrays.sort(arrays);
System.out.println("Minimum value in Arrays : " + arrays[0]);
System.out.println("Miximum value in Arrays : " + arrays[arrays.length - 1]);
I've found the minimum, but how can I square it?
ReplyDeleteimport java.util.HashMap;
ReplyDeleteimport java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class maxMinimumArray {
public static void main(String[] args) {
int[] values = {-20, 34, 21, -87, 92};
int[] sortedArr = sortValues(values);
Map results = maxMinArr(sortedArr);
for(Map.Entry entry : results.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
public static int[] sortValues(int[] arr) {
// sort in asc first (any sort algo will do depending on the complexity you want
// going with bubble sort
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static Map maxMinArr(int[] arr){
Map result = new HashMap<>();
result.put("MinimumValue", arr[0]);
result.put("MaximumValue", arr[arr.length - 1]);
return result;
}
}
public static void findLargestAndSmallestNumberInUnsortedIntArray (int [] unsortedInputArray) {
ReplyDeleteint largest = unsortedInputArray[0];
int smallest = unsortedInputArray[0];
for(int number : unsortedInputArray) {
if(largestnumber) {
smallest=number;
}
}
System.out.println("smallest : "+smallest);
System.out.println("largest : "+largest);
}
int low = Integer.MAX_VALUE; // Initialize with a large value
ReplyDeleteint max = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < low) {
low = arr[i];
}
}
System.out.println(max + " " + low);
int low = Integer.MAX_VALUE; // Initialize with a large value
ReplyDeleteint max = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < low) {
low = arr[i];
}
}
System.out.println(max + " " + low);
This code is completely incorrect. If you have array when first number is smallest you will get wrong result always. Also from mathematical point of view it doesn't make sense to put that smallest number is maximum value of integer and largest number is minimum value of integer, but if you want to solve problem in this way, please correct the solution with two separate if statements instead of if - else if.
ReplyDeleteHello Jovan, good point, the code has a logical issue and will not correctly if the array contains only positive number the smallest will remain Integer.MAX_VALUE as the code will never go into the else-if part (as you mentioned as well).
DeleteHow about this code? does this address the issue?
public static void largestAndSmallest(int[] numbers) {
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
boolean hasNegativeNumber = false; // Flag to check if array contains at least one negative number
for (int number : numbers) {
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
if (number < 0) {
hasNegativeNumber = true;
}
}
// Update smallest only if the array contains at least one negative number
if (!hasNegativeNumber) {
smallest = Integer.MAX_VALUE;
for (int number : numbers) {
if (number < smallest) {
smallest = number;
}
}
}
System.out.println("Given integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}