1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class QuickSort_Better { * Switch a and b */ public static void Swap(int[]a,int left,int right){ int temp=a[left]; a[left]=a[right]; a[right]=temp; } * return median of left ,center and right */ public static int Median3(int []a,int left ,int right){ int center=(left+right)/2; if(a[left]>a[right]) Swap(a,left,right); if(a[left]>a[center]) Swap(a,left,center); if(a[center]>a[right]) Swap(a,center,right); Swap(a,center,left); return a[left]; } public static void quickSort(int[]unsort,int left,int right){ if(unsort==null||left<0||right<=0||right>=unsort.length||left>right){ System.out.println("Invalid Parameters"); } else{ int pivot; if(left<right){ if(right-left+1<=10) InserSort(unsort, left, right); else{ pivot=partition(unsort,left,right); quickSort(unsort,left,pivot-1); quickSort(unsort,pivot+1,right); } } } } public static void InserSort(int[]unsort, int left, int right) { for(int i=left+1;i<right+1;i++){ int temp=unsort[i],j; for(j=i-1;j>=left&&temp<unsort[j];j--) unsort[j+1]=unsort[j]; unsort[j+1]=temp; } } public static int partition(int[] unsort, int left, int right) { int pivotkey=Median3(unsort, left, right); while(left<right){ while(left<right&&unsort[right]>=pivotkey) right--; unsort[left]=unsort[right]; while(left<right&&unsort[left]<=pivotkey) left++; unsort[right]=unsort[left]; } unsort[left]=pivotkey; return left; } public static void main(String args[]){ int []unsorted={6,5,8,2,4,1,7,9,12,10,3,11,6,10,1,1,2,}; quickSort(unsorted,0,unsorted.length-1); for(int i :unsorted){ System.out.print(i+" "); } } }
|