您的位置:首页 > 编程语言 > Go语言

Analysis and implement some simple sorting algorithm.(2)——heapsort

2013-02-19 21:02 399 查看
//modified by quanspace 2013-02-19 20:16
//the time complexity is O(nlgn).
# include <iostream>
# include <cmath>
using namespace std;
class heapsort{
public:
void print_heap(int a[], int a_size);
void max_heapify(int a[], int root, int a_size);
void build_max_heap(int a[], int a_size);
void int_heapsort(int a[], int a_size);
private:
int *heap;
int heap_size;
};
void heapsort::print_heap(int a[], int a_size){
heap = a;  heap_size = a_size;
for(int i = 0; i != heap_size; ++i){
cout<<*(heap+i)<<" ";
}
cout<<endl;
}
//max_heapify is maintain the heap(big root) property.
void heapsort::max_heapify(int a[],int root, int a_size){
int left_child = 2*root;
int right_child = 2*root+1;
int max = 0;
if(left_child<=a_size-1 && a[left_child]>a[root])
max = left_child;
else
max = root;
if(right_child<=a_size-1 && a[right_child]>a[max])
max = right_child;
if(max != root){
int temp = a[root];
a[root] = a[max];
a[max] = temp;
max_heapify(a, max, a_size);
}
}
void heapsort::build_max_heap(int a[], int a_size){
heap_size = a_size;
//regardless of the leaves node of tree.
for(int i = floor((heap_size-1)/2); i>=0; --i){
max_heapify(a, i, heap_size);
}
}

void heapsort::int_heapsort(int a[], int a_size){
heap_size = a_size;
build_max_heap(a, heap_size);
for(int i = heap_size-1; i>=1; --i){
int temp = a[i];
a[i] = a[0];
a[0] = temp;
heap_size = heap_size-1;
max_heapify(a,0,heap_size);
}
}
int main(){
const int arr_size = 10;
int a[arr_size] = {4, 1, 3, 2, 16, 9, 8, 14, 10, 7};
heapsort hs;
cout<<"The original heap is: ";
hs.print_heap(a, arr_size);
hs.int_heapsort(a, arr_size);
cout<<"After heap-sort: ";
hs.print_heap(a, arr_size);
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: