JovenJamsJamesJoe
JovenJamsJamesJoe

Reputation: 1

How to select the largest index of the smallest element in a single array Java

Basically, I need to find the largest index of the smallest element in an array. The first input is the number of elements. However, if the same number is repeated later in the array, it needs to return that index.

Right now my code finds the smallest number and returns the index of that number. How do I update the index?

import java.util.Scanner;

public class smallestelement {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int length = input.nextInt();

        int [] a = new int[length];
        for (int i = 0; i < length; i++){
          a[i] = input.nextInt();
        }

        // minimum 
        int min = a[0]; 
        // counter
        int index = 0; 
        // loop continues as long as i is less than the length of the array
        for (int i = 0; i < a.length; i++){   
              min = a[i];                   
              index = i;
              }
        System.out.println(index);
  }
}

Upvotes: 0

Views: 333

Answers (1)

kaya3
kaya3

Reputation: 51043

You need to use an if statement to check if you are really looking at a smaller element. Use <= to do the comparison, so that when you see an equally-smallest value, the later index is used.

for (int i = 1; i < a.length; i++) {  
    if (a[i] <= min) {
        min = a[i];                   
        index = i;
    }
}

By the way, it's fine for the loop to start at 1 instead of 0, since you initialise min and index before the loop using the value at index 0.

Upvotes: 1

Related Questions