快速排序和堆排序

 

 

 

 

 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*=2)
 6         {
 7             if(j+1<size&&a[j]<a[j+1])
 8             {
 9                 j++;
10             }
11             if(a[j]<=temp)
            break;
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 heap 22 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
27 int temp=a[i]; 28 a[i]=a[0]; 29 a[0]=temp;
         ajustHeap(a, 0,i);
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     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值