数据结构——堆排序
来源:互联网 发布:linq.js下载 编辑:程序博客网 时间:2024/05/13 07:03
#include <iostream>using namespace std;#define LT(a,b) ( (a) < (b) )#define Listsize 100 //表空间的大小可根据实际需要而定,这里假设为100typedef int DataType; //DataType的类型可根据实际情况而定,这里假设为inttypedef 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个元素重新调整为大顶堆 } }//HeapSortint 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;}