Selection Sort

  • average O(n^2) - best O(n^2) - worst O(n^2) - space O(1)
public static void selectionSort(int[] a) {
    if (a == null || a.length <= 1) {
        return;
    }
    for (int i = 0; i < a.length; i++) {
        int idx = i;
        for (int j = i + 1; j < a.length; j++) {
            if (a[j] < a[idx]) idx = j;
        }

        //swap
        if (idx != i) {
            int temp = a[i];
            a[i] = a[idx];
            a[idx] = temp;
        }

}

results matching ""

    No results matching ""