1 //快速排序 2 public static <T extends Comparable> int partion(T a[],int low,int high) 3 { 4 T pivo=a[low]; 5 while(low<high) 6 { 7 while(low<high&&pivo.compareTo(a[high])<=0) 8 { 9 high--; 10 } 11 a[low]=a[high]; 12 while(low<high&&pivo.compareTo(a[low])>=0) 13 { 14 low++; 15 } 16 a[high]=a[low]; 17 } 18 a[low]=pivo; 19 return low; 20 } 21 public static <T extends Comparable> void QSort(T a[],int low,int high) 22 { 23 if(low<high) 24 { 25 int pivoLoc=partion(a, low, high); 26 QSort(a,low,pivoLoc-1); 27 QSort(a,pivoLoc+1,high); 28 29 } 30 }
1 //堆排序 2 public static void ajustHeap(int a[],int s,int size) 3 { 4 int temp=a[s]; 5 for(int j=2*s+1;j<size;j=j*2+1){ 6 if(j+1<size&&a[j]<a[j+1]) 7 { 8 j++; 9 } 10 if(a[j]<=temp){ 11 break; 12 } 13 a[s]=a[j]; 14 s=j; 15 } 16 a[s]=temp; 17 } 18 public static void heapSort(int a[]) 19 { 20 // build heap 21 for(int i=a.length/2-1;i>=0;i--) { 22 ajustHeap(a, i, a.length); 23 } 24 for(int i=a.length-1;i>0;i--) 25 { 26 27 int temp=a[i]; 28 a[i]=a[0]; 29 a[0]=temp; 30 ajustHeap(a, 0,i); 31 } 32 }
1 //测试 2 public static void main(String[] args) { 3 Integer arr[]={3,1,6,2,8,89,4,4,6,9}; 4 int a[]={3,1,6,2,8,89,4,4,6,9}; 5 System.out.println("qsort sort"); 6 QSort(arr,0,arr.length-1); 7 for(Integer i:arr) 8 System.out.print(i+" "); 9 System.out.println("heap sort"); 10 heapSort(a); 11 for(Integer i:a) 12 System.out.print(i+" "); 13 }