/Quick Sort

Quick Sort

Quick Sort

public class Quicksort {

    public static void main(String args[]) {
        int a[] = {4, 2, 3, 1, 6, 5, 0};
        quicksort(a, 0, a.length - 1);
        printArray(a);
    }

    private static void printArray(int a[]) {
        for (int i = 0; i < a.length; i++) {
            if (a.length - 1 == i) {
                System.out.println(a[i]);
                break;
            }
            System.out.print(a[i] + " ");
        }
    }

    private static void quicksort(int a[], int p, int q) {
        if (p <= q) {
            int pivotx = partition(a, p, q);
            quicksort(a, p, pivotx - 1);
            quicksort(a, pivotx + 1, q);
        }
    }

    private static int partition(int a[], int p, int q) {
        int lastelement = a[q];
        int i = p - 1;
        for (int j = p; j < q; j++) {
            if (a[j] < lastelement) {
                i += 1;
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        a[q] = a[i + 1];
        a[i + 1] = lastelement;
        return i + 1;
    }
}