Reputation: 3
I'm trying to implement a selection sort that sorts an integer array but it doesn't do that. I can't figure out what's wrong so maybe another set of eyes can figure it out.
public static void main(String[] args) {
int[] array = {900, 200, 23, -3, 1, 30, 55, -70, 100, 9};
System.out.println(Arrays.toString(array));
for (int i = array.length - 1; i > 0; i--) {
int largest = 0;
for (int j = 1; j <= i; j++) {
if (array[j] > array[largest]) {
}
largest = j;
}
swap(array, largest, i);
}
System.out.println(Arrays.toString(array));
}
private static void swap(int[] arr, int i, int j) {
if (i == j)
return;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Upvotes: 0
Views: 61
Reputation: 1118
Move largest = j
into the if
block
if (array[j] > array[largest]) {
largest = j;
}
Upvotes: 1