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

堆排序C++实例代码

时间:2016-05-20 17:20:21      阅读:192      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!