QUICK SORT IN JAVA
package quicksort;
import java.util.Random;
import java.util.Scanner;
public class Demo {
public static void Display(int A[]){
for(int i=0;i<A.length;i++){
System.out.print(A[i]+" ");
}
}
public static void quicksort(int A[],int start, int end){
if(start>=end){
return;
}
int pIndex=partition(A,start,end);
quicksort(A,start,pIndex-1);
quicksort(A,pIndex+1,end);
}
public static int partition(int a[],int s, int e){
int piviot = a[e];
int pindex=s;
for(int i=s;i<e;i++){
if(a[i]<=piviot){
// swapping
int temp= a[pindex];
a[pindex]=a[i];
a[i]=temp;
pindex++;
}
}
a[e]=a[pindex];
a[pindex]=piviot;
return pindex;
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
Random random=new Random();
int s;
System.out.println("Enter the size of the Array");
s=in.nextInt();
int A[]=new int[s];
for(int i=0;i<s;i++){
A[i]=random.nextInt(100);
}
Display(A);
quicksort(A,0,s-1);
System.out.println("\nSorted");
Display(A);
}
}
0 comments:
Post a Comment