Neocortex 🧠

Search

Search IconIcon to open search

In-Place Quick Sort

Last updated Dec 25, 2021 Edit Source

Implementing Quick Sort in place allows us to decrease the space-complexity of the algorithm and make it slightly more efficient. Here is an in-place implementation of quick sort in java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public static <K> void quickSortInPlace(K[] S, Comparator<K> comp, int a, int b) {
    if (a >= b) {
        return;
    }

    int left = a;
    int right = b - 1;

    K pivot = S[b];
    K temp;                     // temp object used for swapping

    while (left <= right) {
        // scan until reaching value equal or larger than pivot (or right marker)
        while (left <= right && comp.compare(S[left], pivot) < 0) {
            left++;
        }

        // scan until reaching value equal or smaller than pivot (or left marker)
        while (left <= right && comp.compare(S[right], pivot) > 0) {
            right--;
        }

        if (left <= right) {        // indices did not strictly cross
            // so swap values and shrink range
            temp = S[left];
            S[left] = S[right];
            S[right] = temp;
            left++;
            right--;
        }
    }

    // put pivot into its final place (currently marked by left index)
    temp = S[left];
    S[left] = S[b];
    S[b] = temp;
    
    quickSortInPlace(S, comp, a, left - 1);
    quickSortInPlace(S, comp, left + 1, b);
}

Interactive Graph