数据结构 — 堆排序

1、堆排序的时间复杂度与归并排序相同,O(nlogn)。堆排序的优势在与他只需要固定数量的额外空间,堆排序要比空间复杂性为O(n)的归并排序稍微慢一些,但是比空间复杂性为O(1)的归并排序要快。

2、对序列(26, 5, 77, 1, 61, 11, 59, 15, 48, 19)进行堆排序


过程:







代码:

#include<iostream>
using namespace std;
#define max_size 11

void adjust(int list[], int root, int n);
void heapSort(int list[]);

/*
 * 调整最大堆(二叉堆)
 */
void adjust(int list[], int root, int n) {
    int rootkey, child , temp;
    rootkey = temp = list[root];
    child = 2*root;
    while(child <= n) {
        if((child<n) && list[child]<list[child+1]) {
            child++;
        }
        if(rootkey > list[child]) {
            break;
        } else {
            list[child/2] = list[child];
            child *= 2;
        }        
    }
    //向上调整,所以最后要处理root 中的值
    list[child/2] = temp;
}

void heapSort(int list[]) {
    int i, j;
    int n = max_size-1;
    //创建最大堆
    for(i = n/2; i>0; i--) {
        adjust(list, i, n);
    }
    //将root删除(放在数组的最后),调整最大堆
    for(j = n-1; j>0; j--) {
        list[1] = list[1] + list[j+1]- (list[j+1] = list[1]);
        adjust(list, 1, j);
    }
}

int main() {  
       int list[max_size];  
     
       list[1] = 26;  
       list[2] = 5;  
       list[3] = 77;  
       list[4] = 1;  
       list[5] = 61;  
       list[6] = 11;  
       list[7] = 59;  
       list[8] = 15;  
       list[9] = 48;  
       list[10] = 19;  

       for(int i = 1; i<max_size; i++) {  
           cout<<list[i]<<" ";  
       }  
       cout<<endl;  
       heapSort(list);
       for(int i = 1; i<max_size; i++) {  
           cout<<list[i]<<" ";  
       }  
       cout<<endl;  
       return 0;  
   }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeersLee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值