Algorithm backup ---- Heap Sort(堆排序算法)

  Heapsort is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case Θ(n log n) runtime. Heapsort is an in-place algorithm, but is not a stable sort.

  The heap sort works as its name suggests. It begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap and removes the largest remaining item and places it in the next open position from the end of the sorted array. This is repeated until there is no item left in the heap and the sorted array is full.

///   <summary>
///  Heap sort algorithm
///   </summary>
///   <param name="numbers"> numbers to be sorted </param>
///   <param name="length"> number of remaining elements </param>
public   static   void  HeapSort( int [] numbers,  int  length)
{
    
if  (numbers  ==   null   ||  numbers.Length  <=   1 )
        
return ;
    
for  ( int  i  =  (length  /   2 ); i  >   0 ; i -- )
    {
        
if  ( 2   *  i  <=  length  &&  numbers[i  -   1 <  numbers[ 2   *  i  -   1 ])
        {
            Swap(
ref  numbers[i  -   1 ],  ref  numbers[ 2   *  i  -   1 ]);
        }
        
if  ( 2   *  i  +   1   <=  length  &&  numbers[i  -   1 <  numbers[ 2   *  i])
        {
            Swap(
ref  numbers[i  -   1 ],  ref  numbers[ 2   *  i]);
        }
    }
    Swap(
ref  numbers[ 0 ],  ref  numbers[length  -   1 ]);
    
if  (length  >   1 )
        HeapSort(numbers, length 
-   1 );
}

 

Go to my home page for more posts

你可能感兴趣的:(Algorithm)