首页 > 代码库 > 快速排序和堆排序

快速排序和堆排序

 

 

 

 

 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;j<size;j++) 6         { 7             if(j+1<size&&a[j]<a[j+1]) 8             { 9                 j++;10             }11             if(a[j]>temp)12             {13                 a[s]=a[j];14                 s=j;15             }16         }17         a[s]=temp;18     }19     public static void heapSort(int a[])20     {21         // build heap22         for(int i=a.length/2;i>=0;i--)23             ajustHeap(a, i,a.length);24         for(int i=a.length-1;i>0;i--)25         {26             ajustHeap(a, 0,i);27             int temp=a[i];28             a[i]=a[0];29             a[0]=temp;30         }31     }

 

 

 

 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     }

 

快速排序和堆排序