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();
}
}