Find smallest integer value in array list in Java without Arrays.sort
Solution 1
This figure should be helpful :
Then to answer your question, what would you do on paper ?
- Create and initialize the min value at
tenIntArray[0]
- Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at
tenIntArray[0]
) - Loop through the elements of your array
- If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
- You're done
Writing the algorithm should be straightforward now.
Solution 2
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Solution 3
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
Solution 4
The method I am proposing will find both min
and max
.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min
and max
values. Output is:
min: 10
max: 69
Giovanni
Updated on August 01, 2020Comments
-
Giovanni almost 4 years
How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10]; int i, userIn; Scanner KyBdIn = new Scanner(System.in); System.out.println("Please enter 10 integer numbers "); for(i = 0; i < tenIntArray.length; i++){ System.out.println("Please enter integer " + i); userIn = KyBdIn.nextInt(); tenIntArray[i] = userIn; }
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds -
[50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "
The smallest value is 1 at position 5 in array
"