I am trying to sort an array according to example 104.5. It asks you to sort an array from smallest to largest. I've thoroughly scoured through my program several times, but I can't spot my error. Here's the code from my sorting class:
import java.util.Arrays;
public class Sorting {
public static int smallest(int[] array) {
int min = array[0];
for(int i = 0; i < array.length; i++){
if(array[i] < array[0]) {
min = array[i];
}
}
return min;
}
public static int indexOfTheSmallest(int[] array) {
int ind = array[0];
for(int i = 0; i < array.length; i++){
if(array[i] < array[0]) {
ind = i;
}
}
return ind;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int ind = index;
for(int i = index; i < array.length; i++){
if(array[i] < array[index]) {
ind = i;
}
}
return ind;
}
public static void swap(int[] array, int index1, int index2) {
int stor = array[index1];
array[index1] = array[index2];
array[index2] = stor;
}
public static void sort(int[] array) {
int indSmall;
System.out.println(Arrays.toString(array));
for(int i = 0; i < array.length; i++) {
indSmall = indexOfTheSmallestStartingFrom(array, i);
swap(array, indSmall, i);
System.out.println(Arrays.toString(array));
}
}
}
And here's the code I am running:
int[] values = {8, 3, 7, 9, 1, 2, 4};
Sorting.sort(values);
It should output:
[8, 3, 7, 9, 1, 2, 4]
[1, 3, 7, 9, 8, 2, 4]
[1, 2, 7, 9, 8, 3, 4]
[1, 2, 3, 9, 8, 7, 4]
[1, 2, 3, 4, 8, 7, 9]
[1, 2, 3, 4, 7, 8, 9]
[1, 2, 3, 4, 7, 8, 9]
But instead it is outputting:
[8, 3, 7, 9, 1, 2, 4]
[4, 3, 7, 9, 1, 2, 8]
[4, 2, 7, 9, 1, 3, 8]
[4, 2, 3, 9, 1, 7, 8]
[4, 2, 3, 8, 1, 7, 9]
[4, 2, 3, 8, 1, 7, 9]
[4, 2, 3, 8, 1, 7, 9]
[4, 2, 3, 8, 1, 7, 9]