数据结构——堆排序

#include <iostream>
using namespace std;

#define LT(a,b) ( (a) < (b) )
#define Listsize 100 //表空间的大小可根据实际需要而定,这里假设为100
typedef
int DataType; //DataType的类型可根据实际情况而定,这里假设为int
typedef struct
{
DataType data[Listsize];
int len; //顺序表长度
}*SeqList;
typedef SeqList HeapType;

void HeapAdjust(HeapType &H, int low, int length)
{
int temp=H->data[low];
for(int j=2*low; j<=length; j*=2)
{
//沿值较大的孩子结点向下筛选
if(j<length && LT(H->data[j], H->data[j+1]))
++j; //j为值较大的记录的下标
if( !LT(temp, H->data[j]) )
break; //rc应该插入在位置s上
H->data[low] = H->data[j];
low
=j;
}
H
->data[low]=temp; //插入
}//HeapAdjust

//堆排序
void HeapSort(HeapType &H)
{
//对顺序表H进行堆排序
for(int i=H->len/2; i>0; --i) //先把H->data[1...H.len]建成大顶堆
HeapAdjust(H, i, H->len);

for(i=H->len; i>1; --i)
{
swap(H
->data[1], H->data[i]); //H->data[1]是当前堆中最大的元素,将它调到最后面,
//这样一次把最大的元素调到最后面就实现堆排序了

HeapAdjust(H,
1,i-1); //再将剩下的i-1个元素重新调整为大顶堆
}
}
//HeapSort

int main()
{
HeapType H;
H
=(HeapType)malloc(sizeof(HeapType));
if(!H)
{
cout
<<"分配空间失败!"<<endl;
}
H
->len=10;
H
->data[1]=40;
H
->data[2]=55;
H
->data[3]=49;
H
->data[4]=73;
H
->data[5]=12;
H
->data[6]=27;
H
->data[7]=98;
H
->data[8]=81;
H
->data[9]=64;
H
->data[10]=36;

HeapSort(H);
//堆排序
for(int i=1; i<=H->len; i++)
cout
<<H->data[i]<<" ";
cout
<<endl;

return 0;
}

 

posted @ 2010-08-12 10:52  忧国忧铭  Views(521)  Comments(1Edit  收藏  举报