题意:

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

思路:

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

堆排序:

时间复杂度:

最好情况:O(nlogn)

平均情况:O(nlogn)

最坏情况:O(nlogn)

空间复杂度:O(1)

是否稳定:

代码:

 

#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 = 1000000;
int n;
int heap[maxn];

void adjustHeap(int parent,int length){
    int temp = heap[parent];//保存父亲节点的值,因为后边会进行交换
    int child = parent*2;
    while(child<=length){//对以这个节点为根的整棵子树进行调整
        if(child<length && heap[child+1]>heap[child]){//如果是右子树的值更大的话
            child++;//将child的值,定位到右子树的下标
        }
        if(heap[child]<temp){//如果是根节点的值大于孩子节点中的最大值就结束
            break;
        }
        heap[parent] = heap[child];//进行交换
        parent = child;
        child = parent*2;
    }
    heap[parent] = temp;
}

void heapSort(){
    for(int i = n/2; i>0; i--){//从树的中间开始进行调整,因为中间位置就可以调整到整棵树的节点
        adjustHeap(i, n);
    }

    for(int i = n; i>1; i--){
        swap(heap[1], heap[i]);//每一次都会得出一个值,从小到大排序,就将他放到还没有确定好的序列的最后一位
        adjustHeap(1,i-1);
    }
    for(int i = 1; i<=n; i++){
        if(i!=1){
            printf(" ");
        }
        printf("%d",heap[i]);
    }

}

int main(){
    scanf("%d",&n);
    for(int i = 1; i<=n; i++){
        scanf("%d",&heap[i]);
    }
    heapSort();
    return 0;
}
堆排序

相关文章: