Reputation: 59
I use the selection method to solve this problem, but I meet some problems. After seeing answer for it, I found two bugs in my program and then fix it. I am confused about why these two bugs occur, can anyone give me a hand to explain them?
Here is my code:
import java.util.Scanner;
public class JavaTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] myList = new int[5];
for (int i = 0; i < 5; i++){
myList[i] = input.nextInt();
}
for (int i = 0; i < 4; i++){
int j = 0;
// Why do I need to put this outside inner for loop?
int smallest = myList[i];
// Why do I need to give the value of i to index after i increase by 1?
int index = i;
for (j = i + 1; j < 5; j++){
if (smallest > myList[j]){
smallest = myList[j];
index = j;
}
}
if (index != i){
myList[index] = myList[i];
myList[i] = smallest;
}
}
for (int i = 0; i < 5; i++){
System.out.print(myList[i] + " ");
}
input.close();
}
}
Upvotes: 0
Views: 82
Reputation: 8725
Selection algorithm is an algorithm for finding the kth smallest number in a list or array.
Each iteration your algorithm find the smallest number i to myList.length:
First iteration is between 0 to 4
Second iteration is between 1 to 4 and etc...
// Why do I need to put this outside inner for loop? int smallest = myList[i];
After the first iteration the value of "smallest" will be the real smallest number in the list instead of the smallest in indexes 1 to 4, and then the inner loop won't do anything.
// Why do I need to give the value of i to index after i increase by 1? int index = i;
you initialize the index to the current position of your (suspected)smallest number. if the current value of "smallest" is the smallest number in the iteration then the second "for loop" won't do anything.
and then the condition:
(index != i)
will be true even though it shouldn't
Upvotes: 1