Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of the smallest element in an array (Java)

I am trying to write up a block of code that takes an array of integers as an argument and returns the index of the smallest element in the array. Also, the function should return -1 if the list is an empty list.

Test for the block of code.

So far I have got,

public static int indexOfSmallest(int[] array){
    int index = 0;
    int min = array[index];

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

But, I'm getting this error and unsure what I need to fix.

enter image description here

Any help would be much appreciated. Thank you.

like image 652
user430574 Avatar asked Aug 05 '18 09:08

user430574


People also ask

How do you find the smallest item in an array?

Firstly in the function we assign the value of first element to a variable and then we compare that variable value with every other element of array. If the variable is smaller than all other elements, then we return variable which store first element value as smallest element.

How do you find the index of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

The error is self explanatory. You fail to handle the case of empty input array.

public static int indexOfSmallest(int[] array){

    // add this
    if (array.length == 0)
        return -1;

    int index = 0;
    int min = array[index];

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

If the smallest element appears multiple times, and you want to return the index of its first occurrence, change your condition to:

if (array[i] < min) 
like image 62
Eran Avatar answered Oct 06 '22 01:10

Eran