简介
堆排序(英语:Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。时间复杂度是O(n*logn)的,如果有10亿条数据,假设计算机每秒进行运算10亿次,冒泡法需要30年,而堆排序30s就可以完成。
#include<iostream>
using namespace std;
int currentsize;
void siftdown(int * Minheap,int pos)
{
int i =pos;
int temp=Minheap[pos];
int j=2*i+1;
while(j<currentsize)
{
if(j+1<currentsize && Minheap[j+1]<Minheap[j])
j++;
if(temp> Minheap[j])
{
Minheap[i] = Minheap[j];
i=j;
j=j*2+1;
}
else
break;
}
Minheap[i] = temp;
}
void print(int *Minheap,int size) //输出结果
{
for(int i=0;i<size;i++)
{
cout<<Minheap[i]<<" ";
}
cout<<endl;
}
void build(int *Minheap,int size) //建堆
{
for(int i=size/2-1;i>=0;i--)
{
siftdown(Minheap,i);
}
}
int delete_min(int *Minheap)
{
int ans =Minheap[0];
int temp;
temp= Minheap[0];
Minheap[0] = Minheap[--currentsize];
Minheap[currentsize]=temp;
siftdown(Minheap,0);
return ans;
}
void sort(int * Minheap,int size)
{
for(int i=0;i<size-1;i++)
{
delete_min(Minheap);
}
}
int main()
{
int tempsize;
int Minheap[10]={2,73,71,203,94,16,50,68};
currentsize = 8;
tempsize=8;
cout<<"原数组"<<endl;
print(Minheap,currentsize);
cout<<"建堆后的数组"<<endl;
build(Minheap,currentsize);
print(Minheap,currentsize);
cout<<"堆排序后的数组"<<endl;
sort(Minheap,currentsize);
print(Minheap,tempsize);
return 0;
}