您的位置:首页 > 其它

堆排序 heapSort

2010-05-04 10:16 621 查看
堆排序是一种原地(in place)排序算法,二叉堆有两种:最大堆和最小堆
Max_Heapify过程:保持最大堆性质的关键,父结点大于等于子节点,运行时间: O(lgN)
Bulid_Max_Heap过程:遍历整个数组,调用Max_Heapify过程,保持所有元素的最大堆性质,构建最大堆,运行时间:O(n)
Heap_Sort过程:遍历整个数组,交换首位元素,并提取首元素,调用Max_Heapify过程,保持所有元素的最大堆性质,对数组进行原地排序,运行时间:O(nlgn)

Heap-Sort的C++实现如下:
#include <iostream>

inline int Parent(const int & i)
{
return (i - 1) / 2;
}

inline int LChild(const int & i)
{
return 2 * i + 1;
}

inline int RChild(const int & i)
{
return 2 * i + 2;
}

const int GetSizeofArray(const int & i);
void Build_Max_Heap(int a[], const int & size);
void Max_Heapify(int a[], int i, const int & size);
void Heap_Sort(int a[], int size);
int main()
{
int size;

std::cout << "Input the size of heap:" << std::endl;
std::cin >> size;
int length = GetSizeofArray(size);
int * a = new int[length]();
for (int i = 0; i < size; i++)
{
std::cin >> a[i];
}
Build_Max_Heap(a, size);

int temp = 0;	//上一行第一个元素的序数
int j = 1;		//代码每行结点数
for (int i = 0; i < size; i++)
{
if (i - temp == j)
{
std::cout << std::endl;
temp = i;
j *= 2;
}

std::cout << a[i] << "   ";
}
Heap_Sort(a, size);
std::cout << std::endl << "Output the result of heap:" << std::endl;
for (int i = 0; i < size; i++)
{
std::cout << a[i] << " ";
}

delete []a;

/*************************************************
Function: GetSizeofArray
Description:从输入的元素个数来决定数组的大小
Input:const i 输入元素的个数
Return:所需数组的大小
*************************************************/
const int GetSizeofArray(const int & i)
{
int size = 1;
while (size < i)
{
size *= 2;
}
return size;
}

/*************************************************
Function: Build_Max_Heap
Description:从输入的元素个数来决定数组的大小
Input:const i 输入元素的个数
Return:所需数组的大小
*************************************************/
void Build_Max_Heap(int a[], const int & size)
{
int parent = Parent(size - 1);
for ( ; parent >= 0; parent--)
{
Max_Heapify(a, parent, size);
}
}

/*************************************************
Function: Max_Heapify
Description:使堆中指定元素有最大堆的特性
Input:	a[] 指定的堆
i 堆中指定元素的序号
size 堆中可遍历的元素个数
*************************************************/
void Max_Heapify(int a[], int i, const int & size)
{
int lChild = LChild(i);
int rChild = RChild(i);
int max = i;
if (lChild <= size - 1 && a[lChild] > a[max])
{
max = lChild;
}

if (rChild <= size - 1 && a[rChild] > a[max])
{
max = rChild;
}

if (max != i)
{
int temp = a[i];
a[i] = a[max];
a[max] = temp;
Max_Heapify(a, max, size);
}
}

/*************************************************
Function: Heap_Sort
Description:利用不断移动max元素,以及Max_Heapify操作进行排序
Input:	a[] 指定的堆
size 堆中可遍历的元素个数
*************************************************/
void Heap_Sort(int a[], int size)
{
for (int i = 0; i < size - 1; i++)
{
int temp = a[0];
a[0] = a[size - 1 - i];
a[size - 1 - i] = temp;
Max_Heapify(a, 0, size - i - 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: