HI, I have now for more than 24 hours tried to figure out how I return the index number of the second smallest integer in an unsorted array.
Some how, I do not get the index number returned, can any one see what I´m missing?
As the program runs now, it returns the value of the second smallest integer in an array, but I can´t make the program return the index number in the array.
Thanks in advance
public class SecondSmallest {
public static void main(String[] args) {
System.out.println("Næstmindste værdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {1,2,3,4,5})));
}
public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
if (values.length < 2) {
throw new IllegalArgumentException("Der skal være mindst to værdier i arrayet af typen int");
}
int min;// declare variable
int secondMin;// declare variable
// Estblish relation between min and secondMin in the array
if (values[0] < values[1]) {
min = values[0];
secondMin = values[1];
}// end of if
else {
min = values[1];
secondMin = values[0];
}// end of else
for (int i = 0; i < values.length; i++) {
if (values[i] <= min) {
secondMin = min;
min = values[i];
}
else if (values[i] < secondMin) {
secondMin = values[i];
values[i]= secondMin;
}
}//end of for
for (int i = 0; i < values.length; i++) {
if ( values[i] == secondMin ) {
values[i]=secondMin;
//secondMin = i; //Should retrieve indexnumber of secondMin
return secondMin;
}// end of if
// return i;
}// end of forloop
return secondMin;
}// end of static int
}// end of class