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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With