最大堆排序

#include <iostream>
#include <vector>
using namespace std;

inline int leftChild(int i)
{
	return 2*i+1;
}

template <typename Comparable>
void percDown(vector<Comparable>& a,int i,int n)
{
	int child;
	Comparable tmp;

	for(tmp = a[i];leftChild(i) < n;i = child)
	{
		child = leftChild(i);
		if(child != n-1 && a[child] < a[child+1])
			child++;
		if(tmp < a[child])
			a[i] = a[child];
		else
			break;
	}
	a[i] = tmp;
}

template <typename Comparable>
void heapSort(vector<Comparable>& a)
{
	for(int i =a.size()/2-1;i>=0;--i) //buildHeap
		percDown(a,i,a.size());  
	for(int j=a.size()-1;j>0;--j)
	{
		swap(a[0],a[j]);            //delete Max
		percDown(a,0,j);
	}
}

int main()
{
	vector<int> arr;
	int data;
	cin >> data;
	while(data != -1)
	{
		arr.push_back(data);
		cin>>data;
	}
	vector<int>::iterator iter = arr.begin();
	for(;iter != arr.end();++iter)
		cout << *iter << ' ';
	cout << endl;
	return 0;
}

  

原文地址:https://www.cnblogs.com/phoenixzq/p/2190520.html