您的位置:首页 > 其它

排序算法(堆排序)

2016-08-06 16:20 253 查看
堆排序是对选择排序的改进(时间复杂度和希尔排序一样O(nlog2n))

数据结构:完全二叉树(大顶堆,根节点都比左右节点大,小顶堆,根节点小于双亲节点)

public class HeapSort {
public static void main(String[] args) {
int a[]={1,2,4,9,33,2,6,7,10,11};
sort(a, 10);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}

}

//调整堆
public static void heapAdjust(int a[],int s,int n){

int i,temp;
temp=a[s];

for(i=2*s;i<n;i*=2){
if(i+1<n&&a[i]<a[i+1]){
i++;
}

if(temp>=a[i]) break;

a[s]=a[i];
s=i;
}
a[s]=temp;
}

//交换位置
public static void swap(int a[],int i,int j){
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}

//排序
public static void sort(int h[],int n){
int i;
for(i=n/2;i>0;i--){
heapAdjust(h, i, n);
}

for(i=n-1;i>1;i--){
swap(h, 1, i);
heapAdjust(h, 1, i-1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: