首页 > 编程语言 > 详细

堆排序C++实例代码

时间:2016-05-20 17:17:23      阅读:150      评论:0      收藏:0      [点我收藏+]
#include<iostream>
using namespace std;

void display(int *a, int size){
    for(int i = 0 ; i < size; i++){
        cout << a[i] << " ";
    }
    cout << endl;
}

void heapSort(int *a, int i, int size){
     int lc = 2*i,rc = 2*i+1,max = i;
     if(lc <= size && a[max-1] < a[lc-1]){
          max = lc;
     }
      if(rc <= size && a[max-1] < a[rc-1]){
         max = rc;
      }
      if(max != i){
         swap(a[i-1],a[max-1]);
         if(2*max <= size){
             heapSort(a,max,size);
         }
      }
}

void buildHeap(int *a, int size){
    for(int i = size/2;i > 0; i-- ){
        heapSort(a,i,size);
    }
}


int main(){
    int a[] = {16,7,3,20,17,8};
    int size = 6;
    buildHeap(a,size);

    swap(a[0],a[size]);
    size--;
    while(size>1){
        heapSort(a,1,size);
        swap(a[0],a[size]);
        size--;
    }

//    while(--size>0){
//        swap(a[0],a[size]);
//        heapSort(a,1,size);
//    }
    display(a,6);
    return 0;

}

  注释部分对上面的优化。

堆排序C++实例代码

原文:http://www.cnblogs.com/usa007lhy/p/5512737.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!