简体   繁体   中英

Selection sort not sorting integer array

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

Move largest = j into the if block

if (array[j] > array[largest]) {
    largest = j;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM