[大话数据结构] 9.7 堆排序

来源:互联网 发布:淘宝模特图 编辑:程序博客网 时间:2024/04/29 04:28
#include <stdio.h>#include <algorithm>using namespace std;int a[100]={0,2,1,3,6,5,4,9,7,8,0}, len = 10;   //下标从1开始void heapAdjust(int s, int l){    int temp = a[s];    for(int j = 2*s; j <= l; j *= 2)    {        if(j < l && a[j] < a[j+1])        {            ++j;        }        if(a[j] <= temp)        {            break;        }        a[s] = a[j];        s = j;    }    a[s] = temp;}void heapSort(){    int tmp = len / 2;    for(int i = tmp; i > 0; i--)    {        heapAdjust(i, len);    }    for(int i = len; i > 1; i--)    {        swap(a[i],a[1]);        heapAdjust(1, i-1);    }}int main(){    heapSort();    for(int i = 1; i <= 10; i++)    {        printf("%d ", a[i]);    }    getchar();    return 0;}

0 0