Running Time of Quicksort

  • + 2 comments

    import java.io.; import java.util.;

    public class Solution {

    public static int[] a;
    public static int n;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        a = new int[n];
        for(int i = 0; i < n; i++){
            a[i] = in.nextInt();
        }
        quick(0,n-1);
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    }
    static void quick(int l, int h){
        if(h-l<=0)
            return;
        if(h-l == 1){
            if(a[h]<a[l])
                swap(l,h);
            printArray();
            return;
        }
        int p = a[h];
        int q = l;
        for(int i = l; i < h; i++){
            if(a[i] < p){
                if(i > q){
                    swap(i,q);
                    q++;
                }else if(i == q){
                    q++;
                }
            }
        }
        swap(q,h);
        printArray();
        quick(l,q-1);
        quick(q+1,h);
    }
    static void printArray(){
        for(int i = 0; i < n; i++)
            System.out.print(a[i]+" ");
        System.out.println();
    }
    static void swap(int x, int y){
        int temp = a[x];
        a[x] = a[y];
        a[y] = temp;
    }
    

    }