Quick Sort Simplest Code

public class Sort {
 
public static void quick(int a[],int beg, int end){
    if(beg<end){
        int p=partition(a,beg,end);
        quick(a,beg,p-1);
        quick(a,p+1,end);
    }  
}

public static int partition(int a[], int beg, int end){

    int c[]=new int[a.length],l=beg,r=end,pivot=beg;    //variable declaration

    for(int i=beg+1;i<=end;i++){
        if(a[i]<a[pivot]) c[l++]=a[i];
        else c[r--]=a[i];
    }
    c[l]=a[pivot];
    for(int i=beg;i<=end;i++)
        a[i]=c[i];
 
     return l;
}

public static void main(String[] args){
    int a[]={26,19,45,30,34,42,15,18,21,32,36,13,22,33,14,32,42};
    int n=a.length;
    System.out.println("List Before Sorting:-\n\n");
    for(int e:a)
        System.out.print(e+" ");
    System.out.println();
    quick(a,0,n-1);
    System.out.println("List After Sorting:-\n");
   for(int e:a)
        System.out.print(e+" ");
    System.out.println();
    }  
}

Output :

List Before Sorting:-
26 19 45 30 34 42 15 18 21 32 36 13 22 33 14 32 42

Processing...

19 15 18 21 13 22 14 26 42 32 33 36 32 42 34 30 45
15 18 13 14 19 22 21 26 42 32 33 36 32 42 34 30 45
13 14 15 18 19 22 21 26 42 32 33 36 32 42 34 30 45
13 14 15 18 19 22 21 26 42 32 33 36 32 42 34 30 45
13 14 15 18 19 21 22 26 42 32 33 36 32 42 34 30 45
13 14 15 18 19 21 22 26 32 33 36 32 34 30 42 45 42
13 14 15 18 19 21 22 26 30 32 34 32 36 33 42 45 42
13 14 15 18 19 21 22 26 30 32 32 33 34 36 42 45 42
13 14 15 18 19 21 22 26 30 32 32 33 34 36 42 45 42
13 14 15 18 19 21 22 26 30 32 32 33 34 36 42 42 45

List After Sorting:-

13 14 15 18 19 21 22 26 30 32 32 33 34 36 42 42 45 

Popular posts from this blog

8 Bit Plane Slicing of an image in Image Processing

Code to upload multiple files simultaneously using JSP, Servlet .

STRING PALINDROME USING STACK AND QUEUE