Site Search:

Quick Sort

Quick sort is a sorting algorithm with O(NlogN) time complexity and O(1) space complexity. The worst case time complexity is O(N^2). It is unstable.

Code:

public class QuickSort {
    public static void main(String...args) {
        int[] a = { 2, 5, 7, 3, 5, 9, 0};
        QuickSort qs = new QuickSort();
        qs.sort(a);
        for(int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
    
    public void sort(int[] a) {
        sort(a, 0, a.length - 1);
    }
    
    private void sort(int[] a, int lo, int hi) {
        if(lo >= hi) return;
        int mid = partition(a, lo, hi);
        sort(a, lo, mid - 1);
        sort(a, mid + 1, hi);
    }
    
    private int partition(int[] a, int lo, int hi)  {
        int v = a[lo];
        int i = lo;
        int j = hi + 1;
        while(true) {
            while(a[++i] <= v) if(i == hi) break;
            while(a[--j] >= v) if(j == lo) break;
            if(i >= j) break;
            exch(a, i, j);
        }
        exch(a, lo, j);
        return j;
    }
    
    private void exch(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

}

Examples: