Algorithm 4_Heap_Sort
来源:互联网 发布:淘宝搜索优化 编辑:程序博客网 时间:2024/06/03 16:42
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:
{
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.
{
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.
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).
- Algorithm 4_Heap_Sort
- 堆排序_heap_sort
- Cake Cutting Algorithm -4 : Trimming Algorithm
- Algorithm 4th edition
- Algorithm
- Algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- Algorithm
- Algorithm
- algorithm
- Algorithm
- Algorithm
- algorithm
- algorithm
- Win XP/2003的预读取文件
- XP的小游戏移植到Win2003
- Win2003下提高FSO的安全性
- 驯服Windows Server 2003
- 地磅称量系统之(41~50) 创建自己的Icon文件作为位图
- Algorithm 4_Heap_Sort
- ASP判断远程图片是否存在函数
- 地磅称量系统之(51)应用自己创建的Icon文件作为位图
- 2008脚本大赛PowerShell Sudden Death Event 6解题及分析
- 检查用户名是否已存在
- 改变一下编译原理学习策略
- 人工智能领域的重要会议
- SAP SD Tables
- 地磅称量系统之(52)制作应用程序的托盘功能(显示在操作系统的时间左边的小图标)