GiovanniL GiovanniL - 3 months ago 19
Java Question

Find smallest integer value in array list in Java without Arrays.sort

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
"

Answer

This figure should be helpful :

enter image description here

Then to answer your question, what would you do on paper ?

  1. Create and initialize the min value at tenIntArray[0]
  2. 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])
  3. Loop through the elements of your array
  4. 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
  5. You're done

Writing the algorithm should be straightforward now.

Comments