堆排序

自己参考算法导论实现的

/**********************************************************
**	Heap sorting. More details can be found in
**	Chapter 6.4 in Introduction to Algorithms(2nd Edition)
**
***********************************************************/
#include <iostream>

using namespace std;

void maxHeap(int arr[], int n, int i)
{
	int left = 2*i;
	int right = 2*i+1;
	int maxval = i;

	if (left<=n && arr[left]>arr[maxval])
	{
		maxval = left;
	}

	if (right<=n && arr[right]>arr[maxval])
	{
		maxval = right;
	}

	if (maxval!=i)
	{

		swap(arr[i],arr[maxval]);
		maxHeap(arr,n,maxval);
	}

}
void BuildHeap(int arr[], int n)
{
	if (n==0)
	{
		return;
	}

	for (int i = n>>1; i > 0; --i)
	{
		maxHeap(arr,n,i);
	}
}

void heapSort(int arr[], int n)
{
	if (n==0)
	{
		return;
	}

	BuildHeap(arr,n);

	for (int i = n; i > 1; --i)
	{
		swap(arr[1],arr[i]);
		maxHeap(arr,i-1,1);
	}
}


int main()
{
	
	int arr[] = {-1,1,3,5,7,2,4,6,8,9};
	int n = sizeof(arr)/sizeof(arr[0])-1;

	for (int i=1;i<=n;i++)
	{	
		cout << arr[i] << " ";
	}
	cout << endl;

	heapSort(arr,n);

	for (int i=1;i<=n;i++)
	{	
		cout << arr[i] << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}



你可能感兴趣的:(堆排序)