最近在复习数据结构,文章所使用c++,因时间仓促,使用的是较简单的C风格,稍作改动即可面向对象操作。代码粗糙:
#include <iostream>
#include <algorithm>
using namespace std;
int *heap;
int n;
void heapadjast(int start,int length)
{
int cur=start;
int child=start*2+1;
int temp=heap[cur];
while(child<=length)
{
if(child+1<=length&&heap[child+1]<heap[child])child++;
if(temp<heap[child])
break;
else
{
heap[cur]=heap[child];
cur=child;
child=2*child+1;
}
}
heap[cur]=temp;
}
void swep(int *a,int i,int j)
{
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
void heapsort()
{
for(int i=(n-2)/2;i>=0;i--)
{
heapadjast(i,n-1);
}
/*for(int i=n-1;i>0;--i)
{
swep(heap,0,i);
heapadjast(0,i-1);
}*/
}
void siftUP(int pos)
{
int cur=pos;
int par=(pos-1)/2;
int temp=heap[cur];
while(cur)
{
if(temp>=heap[par])
break;
else
{
heap[cur]=heap[par];
cur=par;
par=(par-1)/2;
}
}
heap[cur]=temp;
}
void insertq(int num,int *heap)
{
heap[n]=num;
n++;
siftUP(n-1);
}
void removeq()
{
heap[0]=heap[n-1];
n--;
heapadjast(0,n-1);
}
int main()
{
int Maxsize=20;
int arr[]={0,9,5,1,4,7,11,13,12,111};
n=0;
heap=new int[Maxsize];
for(int i=0;i<10;i++)
{
insertq(arr[i],heap);
}
heapsort();
insertq(6,heap);
for(int i=0;i<n;i++)
cout<<heap[i]<<" ";
cout<<endl;
while(n)
{
cout<<heap[0]<<" ";
removeq();
}
}