1. 程式人生 > >堆排序,分別利用大根堆、小根堆排序

堆排序,分別利用大根堆、小根堆排序

#include <iostream>
using namespace std;
//下沉調整(本質上都是上浮調整,只不過是將最小元素上浮)
void downAdjust(int array[],int parentIndex,int length)
{
	int temp = array[parentIndex];
	int childIndex = 2 * parentIndex + 1;
	while (childIndex < length)     
	{
		if ((childIndex +1< length) &&(array[childIndex + 1] < array[childIndex])) //如果右孩子更小的話,則指向右孩子
		{
			childIndex++;
		}
		if (temp < array[childIndex])
			break;
		array[parentIndex] = array[childIndex];
		parentIndex = childIndex;
		childIndex = 2 * childIndex + 1;
	}
	array[parentIndex] = temp;
}
//上浮調整
void upAdjust(int array[], int parentIndex, int length)
{
	int temp = array[parentIndex];
	int childIndex = 2 * parentIndex + 1;
	while (childIndex < length)
	{
		if (childIndex + 1 < length&&array[childIndex] < array[childIndex + 1])//如果右孩子更大則childIndex指向右孩子
		{
			childIndex++;
		}
		if (temp >= array[childIndex])
			break;
		array[parentIndex] = array[childIndex];
		parentIndex = childIndex;
		childIndex = childIndex * 2 + 1;
	}
	array[parentIndex] = temp;
	
}
//利用下沉調整構建堆
void downBuildHeap(int array[], int length)
{
	for (int i = length/2 -1; i >= 0; i--) //注意最後一個非葉子結點是length/2-1
	{
		downAdjust(array, i, length);
	}
}
//利用上浮調整構建堆
void upBuildHeap(int array[], int length)
{
	for (int i = length / 2 - 1; i >= 0; i--)
	{
		upAdjust(array, i, length);
	}
}
int main()
{
	int array[16] = { 7,1,3,10,5,2,8,9,6,11,22,15,100,56,78,53 };
	downBuildHeap(array,sizeof(array) / sizeof(array[0]));
	cout << "downadjust: ";
	for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++)
		cout<< array[i]<<" ";
	//利用小根堆排序
	cout << endl;
	for (int j = sizeof(array) / sizeof(array[0]) - 1; j > 0; j--)
	{
		int temp = array[j];
		array[j] = array[0];
		array[0] = temp;
		//for (int i = j / 2 - 1; i >= 0; i--)
			//downAdjust(array, i, j); //child+1<length是可以不讓剛替換的最小根節點被上浮
		downAdjust(array, 0, j);       //這裡只用一次從根節點往下的下沉,是因為初始堆已經是小根堆了,每一個結點的左右孩子都比父節點大,比如第二第三小的結點已經成為根節點的左右孩子,因而進行一次從
									   //根節點往下的下沉操作即可重新調整為小根堆,大根堆同理
	}
	cout << "after sort :";
	for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++)
		cout << array[i] << " ";
	cout << endl;

	int another_array[16] = { 7,1,3,10,5,2,8,9,6,11,22,15,100,56,78,53 };
	upBuildHeap(another_array, sizeof(another_array) / sizeof(another_array[0]));
	cout << "upadjust: ";
	for (int i = 0; i < sizeof(another_array) / sizeof(another_array[0]); i++)
		cout << another_array[i] << " ";
	//利用大根堆排序
	cout << endl;
	for (int j = sizeof(another_array) / sizeof(another_array[0]) - 1; j > 0; j--)
	{
		int temp = another_array[j];
		another_array[j] = another_array[0];
		another_array[0] = temp;
		//for (int i = j / 2 - 1; i >= 0; i--)
			//upAdjust(another_array, i, j); //child+1<length是可以不讓剛替換的最大根節點被上浮
		upAdjust(another_array, 0, j);
		
	}
	cout << "after sort :";
	for (int i = 0; i < sizeof(another_array) / sizeof(another_array[0]); i++)
		cout << another_array[i] << " ";
	return 0;
}