First of all,the binary heap is an array that can be viewd as a nearly completely binary tree.Each node of the tree corresponds to an element of the arrau that stores the value in the node.
We can simply implement the heap as following codes:
class Heap
{
private Int32 size;
public Int32 Size
{
get { return size; }
set { size = value; }
}
public Int32 Parent(Int32 index)
{
return (index-1)/2;
}
public Int32 Left(Int32 index)
{
return index * 2 + 1;
}
public Int32 Right(Int32 index)
{
return index * 2 + 2;
}
}One important function in this algorithm is MaxHeapify().Its input are an array A and an index I into the array.When this is called,it is assumed that the binary tree rooted at Left(i) and Right(i) are max heaps,but the A[i] may be smaller than its children,this violating the max heaps.This function is to let the value at A[i] float down in the max heao so that the subtree rooted at index I becomes a man heap.
Let’s show you the code.
private static void MaxHeapify(Int32[] arr, Int32 index)
{
Int32 left = heap.Left(index);
Int32 right = heap.Right(index);
Int32 largest;
if (left < heap.Size && arr[left] > arr[index])
largest = left;
else
largest = index;
if (right < heap.Size && arr[right] > arr[largest])
largest = right;
if (largest != index)
{
Swap(arr, index, largest);
MaxHeapify(arr, largest);
}
}But before this function ,we need build a max heap from an array.
//create a max heap from an array
private static void BuildMaxHeap(Int32[] arr)
{
heap.Size = arr.Length;
for (Int32 index = (arr.Length - 1) / 2; index >= 0; index--)
{
MaxHeapify(arr, index);
}
}So, we can sort write the algorithm simply.
public static void Sort(Int32[] arr){
BuildMaxHeap(arr);
for (Int32 index = arr.Length - 1; index > 0; index--)
{
Swap(arr, 0, index);
heap.Size--;
MaxHeapify(arr, 0);
}
}
Heapsort’s running time is O(nlgn).
本文介绍了一种基于二叉堆数据结构的高效排序算法——堆排序。首先定义了二叉堆的概念,并给出了实现堆的关键操作,如调整最大堆(MaxHeapify)等。接着详细解释了如何从数组构建最大堆并进行排序的过程。
454

被折叠的 条评论
为什么被折叠?



