I'm doing mooc.fi, my code works but it won't submit.
errors I'm getting
the method swap does not work correctly with parameter 4, 7, 8, 6 index1=0 index2=3
the result was 4, 7, 8, 6 but it should have been 6, 7, 8, 4
and
the method sort does not work correctly with parameter 10, 20, 6, -1, 13, 11
the result was 10, 20, 6, -1, 13, 11 but it should have been -1, 6, 10, 11, 13, 20
I know the errors are connected but I'm not too sure what to do to fix this, any help is appreciated! thank you!
My Code:
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int start = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < start) {
start = array[i];
}
}
return start;
}
public static int indexOfTheSmallest(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == smallest(array)) {
return i;
}
}
return 0;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int minIndex = index;
for (int i = index; i < array.length; i++) {
if (array[i] < array[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
public static void swap(int[] array, int index1, int index2) {
int hold = 0;
for (int i = 0; i < array.length; i++) {
hold = array[index1];
array[index1] = array[index2];
array[index2] = hold;
}
}
public static void sort(int[] array) {
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
swap(array, i, indexOfTheSmallestStartingFrom(array, i));
System.out.println(Arrays.toString(array));
}
}
public static void main(String[] args) {
int[] values = {8, 5, 3, 7, 9, 6, 1, 2, 4};
sort(values);
}
}