码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2018-05-24 00:37:30      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:turn   return   std   ios   iostream   clu   div   class   bre   

 

#include"iostream"
#include"time.h"
using namespace std;
void show(int *a,int n){
    for(int i = 0;i < n;i++){
        cout<<a[i]<<ends;
    }
    cout<<endl;
}
void buildheap(int *a,int s,int n){
    int temp = a[s];
    for(int i = 2 * s + 1;i < n;i = i * 2 + 1){
        if(i < n - 1 && a[i] < a[i + 1]){
            i++;
        }
        if(temp < a[i]){
            a[s] = a[i];
            s = i;
        }
        else{
            break;
        }
    }
    a[s] = temp;
}
//堆排序
void heapsort(int *a,int n){
    for(int i = n / 2;i >= 0;i--){
        buildheap(a,i,n);
    }
    for(i = n - 1;i >= 0;i--){
        int temp = a[i];
        a[i] = a[0];
        a[0] = temp;
        buildheap(a,0,i);
    }
}
int main(){
    const int N = 10;
    int a[N];
    srand(time(NULL));
    for(int i = 0;i < N;i++){
        a[i] = rand() % 10;
    }
    show(a,N);
    heapsort(a,N);
    show(a,N);
    return 0;
}

 

堆排序

标签:turn   return   std   ios   iostream   clu   div   class   bre   

原文地址:https://www.cnblogs.com/oleolema/p/9080503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!