您的位置:首页 > 编程语言 > Java开发

今天开始学Java 排序算法之堆排序

2018-03-09 23:06 316 查看
大顶堆用于升序排列:经过多次比较把最大的元素放到根结点(相当于找到序列里面的最大元素),然后再将这个最大元素放到叶结点,这个叶结点就固定不动了,继续比较其它结点,从剩下的结点里面供一个最大元素出来放到根结点,依次循环。
public class InsertSort {
public static void sort(int[] a){
//formulate the bigtoptree
for(int i = a.length/2-1;i>=0;i--){
adjustHeap(a,i,a.length);
}
// change the top to the butten
for(int j =a.length-1;j>0;j--)

swap(a,0,j);//将堆顶元素与末尾元素进行交换
adjustHeap(a,0,j);
}

}

public static void adjustHeap(int [] a,int i ,int len){
//adjust the Heap
   int tmp=a[i];
   //这里不要偷懒写成a.length,不然可能只能得到大顶堆
   for(int k=i*2+1;k<len;k=k*2+1){
   //if the right Node > the left Node
   if(k+1<len &&a[k+1] >a[k] ){
   k=k+1;
   }
   //if the son Node > father Node,let father's valuse equal the son's valuse
   if(a[k] >tmp){
   a[i] = a[k];
     i=k;
   }else{break;}
   }
   a[i] = tmp;
}
public static void swap(int []arr,int a ,int b){
        int temp=arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {4,5,8,1,9,3,0};
sort(a);
for(int i = 0;i<a.length;i++){
System.out.print(a[i]+" ");
}

       
       }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: