I am supposed to create an algorithm that sorts according to these steps:
Method 1
Select the lowest number in the list and swap with the first number.
Select the lowest number in the list and swap with the second number. Start checking from the second number.
Select the lowest number in the list and swap with the third number. Start checking from the third number.
Select the lowest number in the list and swap with the fourth number. Start checking from the fourth number.
Repeat…until you reach the last number.
Currently, this is the code I have come up with:
public static void method1() {
int low = 999;
int index = 0;
int safe;
int[] num = new int[] { 33, 22, 8, 59, 14, 47, 60, 27 };
for(int i = 0; i < num.length; i++) {
if(low > num[i]) {
low = num[i];
index = i;
}
}
for (int i = 0; i < num.length; i++) {
safe = num[i];
num[i] = num[index];
low = 999;
for(int j = (i+1); j < num.length; j++) {
if(low > num[j]) {
low = num[j];
}
}
}
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] +", ");
}
}
The output looks like this:
run:
8, 8, 8, 8, 8, 8, 8, 8,
BUILD SUCCESSFUL (total time: 0 seconds)
Why am I only getting values of 8 in the output? As this is homework, please don't tell me the answer. I would only like guidance, thanks!
EDIT:
Code now looks like this:
int low = 999;
int index = 0;
int safe;
int[] num = new int[] { 33, 22, 8, 59, 14, 47, 60, 27 };
for(int i = 0; i < num.length; i++) {
if(low > num[i]){
low = num[i];
index = i;
}
}
for (int i = 0; i < num.length; i++) {
safe = num[i];
num[i] = num[index];
low = 999;
for(int j = (i+1); j < num.length; j++) {
if(low > num[j]){
low = num[j];
index = j;
}
}
}
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] +", ");
}
System.out.println("");
Which gives me an output of:
run:
8, 8, 8, 14, 14, 27, 27, 27,
BUILD SUCCESSFUL (total time: 0 seconds)
safeand you're setting incorrect values in yournum[i] = num[index];line. Focus on that.indexis set and updated.numand setting the value at every index tonum[index], which is the "lowest" value you've determined in your first loop.