0

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;
}
1

1 Answer 1

1

Move largest = j into the if block

if (array[j] > array[largest]) {
    largest = j;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.