7-1 排序 (25 分)

题意:

对给出的数字按由小到大进行排序。

思路:

之前一直没有用过堆排序,借这个题练习一下堆排序。

代码:

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define MAX 1e9;
#define FRE() freopen("in.txt","r",stdin)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 1000010;
int a[maxn];

struct HeapSort {
    void adjustHeap(int* buf, int parent,int length) {
        int temp = buf[parent];//记录父亲节点
        int child = parent*2;//获得左孩子下标

        while(child <= length) {
            if(child<length && buf[child]<buf[child+1]) {//如果范围内的右孩子更大的话
                child++;
            }

            if(temp >= buf[child]) {//如果父亲节点的值,比孩子最大值还要大,直接退出
                break;
            }

            buf[parent] = buf[child];//将孩子节点值,赋给父亲节点
            parent = child;//从孩子开始继续调整
            child = child*2;
        }

        buf[parent] = temp;
    }

    void toSort(int* buf,int length) {
        for(int i = length/2; i>0; i--) {//建堆
            this->adjustHeap(buf, i, length);
        }

        for(int i = length; i>1; i--) {
            swap(buf[i], buf[1]);//将第一个数与当前的进行调换
            this->adjustHeap(buf,1,i-1);
        }

        for(int i = 1; i<=length; i++) {
            if(i!=1)
            { printf(" "); }
            printf("%d",buf[i]);
        }
    }
};



int main() {
    int n;
    cin>>n;
    for(int i = 1; i<=n; i++) {
        cin>>a[i];
    }
    HeapSort hs;
    hs.toSort(a, n);
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/sykline/p/10080393.html