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

//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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值