堆排序是一种高级的选择排序,算法代码如下:

 

#include<iostream>
using namespace std;

void heapAdjust(int a[], int low, int high)
{
	int pivotKey = a[low - 1];
	int i;
	for(i = 2 * low; i <= high; i *= 2) 
	{
		if(i < high && a[i - 1] < a[i])
			i++; //i指向较大值
		if(pivotKey >= a[i - 1])
			break;
		a[low - 1] = a[i - 1];
		low = i; //i沿较大孩子结点调整
	}
	a[low - 1] = pivotKey; //恢复
}

void heapSort(int a[], int n)
{
	int i, tmp;
	for(i = n/2; i > 0; i--) //从最后一个非叶子结点处开始调整
		heapAdjust(a, i, n);
	for(i = n; i > 1; i--)
	{
		tmp = a[i -1];
		a[i - 1] = a[0];
		a[0] = tmp;
		heapAdjust(a, 1, i - 1); //只需进行一次调整
	}
}

int main()
{
	int a[] = {4, 5, 1, 3, 2, 0, -3 ,-20, 100, 50};
	heapSort(a, 10);
	int i;
	for(i = 0; i < 10; i++)
		cout << a[i] << " ";
	cout << endl;
    return 0;
}
 


 


本文转载:CSDN博客