Tuesday, 21 August 2012

To implement Quick sort.

                                                                                                                                                                                          //program for quick sort import java.util.*; class Quick { static int partition(int a[],int left,int right) { int i,j,x,t; i=left; j=right; x=a[left]; while(i<j) { while(i<=right&&a[i]<=x) i++; while(a[j]>x) j--; if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } }//end of whie //swap a[j] and a[left] t=a[j]; a[j]=a[left]; a[left]=t; return j; }//end of partition static void quicksort(int a[],int left,int right) { int p; if(left<right) { p=partition(a,left,right); quicksort(a,left,p-1); quicksort(a,p+1,right); } } } class Quicktest { public static void main(String args[]) { System.out.println("Enter number of elements"); Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; Quick q=new Quick(); for(int i=0;i<n;i++) { System.out.println("Enter element"+(i+1)); a[i]=s.nextInt(); } q.quicksort(a,0,n-1); for(int i=0;i<=n-1;i++) System.out.println(a[i]); }//end of main }//end of Quicktest Output ======================================================= C:\Program Files\Java\jdk1.7.0_02\bin>javac Quicktest.java C:\Program Files\Java\jdk1.7.0_02\bin>java Quicktest Enter number of elements 5 Enter element1 156 Enter element2 654 Enter element3 98 Enter element4 175 Enter element5 154 98 154 156 175 654

No comments:

Post a Comment