堆排序练习题

#include <vector>
using namespace std;
class HeapSort
{
private:
	int len;
	vector<int> list;
	void SwapNode(int i,int heapSize);
public:
	void Sort();
	void Print();
	HeapSort(void);
	~HeapSort(void);
};

#include <iostream>
#include "HeapSort.h"
using namespace std;
HeapSort::HeapSort(void)
{
	len = 10;
}
HeapSort::~HeapSort(void){}
void HeapSort::SwapNode(int i,int heapSize)
{
	int l = i*2;
	int r = i*2 +1 ;
	
	int max = i;
	if(l<=heapSize && list[l-1] > list[i-1])
		max = l;
	if(r<=heapSize && list[r-1] > list[l-1])
		max = r;
	
	if(max != i)
	{
		int tmp = list[max-1];
		list[max-1] = list[i-1];
		list[i-1] = tmp;
		SwapNode(max,heapSize);
	}
}

void HeapSort::Sort()
{
	for(int i=len/2;i>0;i--)
	{
		SwapNode(i,len);
	}

	int heapSize = len;
	for(int i=len-1;i>0;i--)
	{
		int tmp = list[i];
		list[i] = list[0];
		list[0] = tmp;
		SwapNode(1,--heapSize);
	}
}
void HeapSort::Print()
{
	for(int i=0;i<len;i++)
	{
		int rnd = rand()%100;
		list.push_back(rnd);
		cout<<rnd << " ";
	}
	cout<<endl;
	Sort();
	for(int i=0;i<len;i++)
	{
		cout<<list[i]<<" ";
	}
	cout<<endl;
}

堆排序是默认把数组看作一个二叉树,第一步是把数组顺序按从小到大由顶向下调整(最大堆),

第二步,取出堆(树)中的最后一个数,并把这个数放在堆顶,把最大的堆顶的数拿出。改变堆的元素个数(已经拿掉了个数),从新调整堆顶的那个比较小的数。

第二步显然有大量无意义的对比。 大致看来 堆排序性能不高,复杂度最高最低都是nlogn

posted @ 2011-05-21 23:25  君之蘭  阅读(2818)  评论(0编辑  收藏  举报