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

堆排序(C++版)

时间:2016-02-29 23:12:54      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>

using namespace std;

void HeapAdjust(int* a, int start, int n)
{
    int max=start;
    int lchild = start*2+1;
    int rchild = start*2+2;
    if(start <= (n-1)/2){
        if(lchild <=n && a[lchild]>a[max]){
        max = lchild;
        }
        if(rchild <=n && a[rchild]>a[max]){
            max = rchild;
        }
        if(max!=start){
            swap(a[start], a[max]);
            HeapAdjust(a, max, n);
        }
    }
}

void BuildHeap(int* a, int n){  //n: [0,n]
    for(int i = (n-1)/2; i >=0;i--){
        HeapAdjust(a, i, n);
    }
}


void HeapSort(int *a,int n)
{
    BuildHeap(a,n);
    for(int i=n;i>=0;i--)
    {
        swap(a[0],a[i]);
        HeapAdjust(a,0,i-1);
    }
}

int main(int argc, char *argv[])
{
    int a[]={6,36,77,31,181,7,8};
    BuildHeap(a,6);
    for(int i=0;i<7;i++){
        cout << a[i] <<endl;
    }
    cout << "=================" <<endl;
    HeapSort(a,6);
    for(int i=0;i<7;i++){
        cout << a[i] <<endl;
    }
    return 0;
}

 

堆排序(C++版)

标签:

原文地址:http://www.cnblogs.com/lifeinsmile/p/5228989.html

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