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.
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.
Any help would be much appreciated. Thank you.
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)