[数据结构] 堆排序算法

来源:互联网 发布:微信机器人 java 编辑:程序博客网 时间:2024/04/30 11:53
#include <iostream>#define MAX_SIZE 100using namespace std;typedef int keytype; typedef struct records          //排序类型 {keytype key;//fields other; };typedef records LIST[MAX_SIZE]; //排序数组void Swap(records &x, records &y){records temp;temp = x;x = y;y = temp;}void PushDown(LIST list, int first, int last)//整理堆,把list[first]中的数据推到堆中的适当位置 {int r;r = first;while(r <= last/2){if((r == last/2) && (last%2 == 0))//r有一个儿子,在2*r {    if(list[r].key > list[2*r].key)  Swap(list[r], list[2*r]);r = last; }else if((list[2*r].key < list[r].key) && (list[2*r].key <= list[2*r+1].key))    //将list[r]和左儿子交换     {    Swap(list[r], list[2*r]);    r = 2*r;             }    else if((list[r].key > list[2*r+1].key) && (list[2*r+1].key < list[2*r].key))    //将list[r]和右儿子交换     {        Swap(list[r], list[2*r+1]);        r = 2*r+1;    }    else        r = last;    }}void Sort(int n, LIST list)//堆排序,将数组元素A[1],…,A[n]排成不增的序列 {   int i;   for(i = n/2; i >= 1; i--)//初始建堆      PushDown(list, i, n);   for(i = n; i >= 2; i--)   {       Swap(list[1], list[i]);//取出堆中最小元素        PushDown(list, 1, i-1);//整理堆    }}int main(){LIST list;int i;cout << "Input the number of array:" << endl;cin >> list[0].key;for(i = 1; i <= list[0].key; i++)  cin >> list[i].key;            Sort(list[0].key, list);            for(i = 1; i <= list[0].key; i++)  cout << list[i].key;return 0;}

0 0
原创粉丝点击