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:

    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).
原创粉丝点击