sdnu1521手写堆排

来源:互联网 发布:思迅会计软件 编辑:程序博客网 时间:2024/05/17 07:45

1521.排序
Time Limit: 1000 MS Memory Limit: 32768 KB
Total Submission(s): 83 Accepted Submission(s): 32
Description
将输入的数从小到大排序。
Input
输入数据n(1<=n<=1000000)

接下来输入n个数据

(多组输入数据)
Output
按格式输出排序后的n个数。
Sample Input

5
5 3 4 6 8

Sample Output

3 4 5 6 8

Source
Unknown

#include<cstdio>#include<iostream>#include<map>#include<set>#include<cstring>using namespace std;int num[1000001];void heapadjust(int heap[], int parent, int nodes){    int temp = heap[parent];        //temp保存当前父节点    int son = parent << 1;          //先获得左孩子 << 1 = *2    while(son <= nodes)    {        // 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点        if(son+1 <= nodes && heap[son] < heap[son+1]){            son ++;        }        // 如果父结点的值已经大于孩子结点的值,则直接结束        if(temp > heap[son]){            break;        }        // 把孩子结点的值赋给父结点        heap[parent] = heap[son];        // 选取孩子结点的左孩子结点,继续向下筛选        parent = son;        son = son << 1;    }    heap[parent] = temp;}void heapbuild(int heap[], int nodes){    // 循环建立初始堆    for(int i = nodes/2; i>=1; i--){        heapadjust(heap, i, nodes);    }    return ;}void heapsort(int heap[], int nodes){    heapbuild(heap, nodes);    // 进行n-1次循环,完成排序    for(int i=nodes; i>1; i--){        // 最后一个元素和第一元素进行交换        int temp = heap[i];        heap[i] = heap[1];        heap[1] = temp;        // 筛选 R[1] 结点,得到i-1个结点的堆        heapadjust(heap, 1, i-1);    }}int main(){    int n, i;    while(scanf("%d", &n)!=EOF)    {        for(i=1; i<=n; i++){            scanf("%d", num+i);        }        heapsort(num, n);        for(i=1; i<n; i++){            printf("%d ", *(num+i));        }        printf("%d\n", num[n]);        memset(num, 0, sizeof(num));    }    return 0;}