Heap Sort - recursion

时间:2023-03-09 08:29:49
Heap Sort - recursion

Heap Sort 

  1. Build a max heap using exsiting array, which is called Heapify
  2. Swap root with the last element, and re-Heapify the root node

Heapify

Heapify(array, n, i) = 1) compare node[i] with children   2)node[i] is already the largest one, no op.  3) child is largest one, swap, then Heapify(array, n, 2*i + 1 or 2i* + 2)

Code

    public class HeapSort
{
/// <summary>
/// Heapify the array
/// </summary>
/// <param name="array">array</param>
/// <param name="n">total size of the heap</param>
/// <param name="i">starting node</param>
public void Heapify(int[] array, int n, int i)
{
int left = *i + ;
int right = *i + ; int largest = i; if (left < n)
{
if (array[left] > array[largest]) // <---- 此处注意,要用array[largest] instead of array[i], 这样我们可以一直跟踪最大的下标, 而不会错误的交换次大的下标
{
largest = left;
}
} if (right < n)
{
if (array[right] > array[largest])
{
largest = right;
}
} if (largest != i)
{
int temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, n, largest);
}
} public void BuildHeap(int[] array)
{
for(int i = array.Length / - ; i >= ; i--)
{
Heapify(array, array.Length, i);
}
} public void Sort(int[] array)
{
if (array == null || array.Length == )
{
return;
} BuildHeap(array); for(int i = array.Length - ; i >= ; i--)
{
Swap(ref array[], ref array[i]);
Heapify(array, i, );
}
} public void Print(int[] array)
{
for(int i = ; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
} private void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}

Comments

  1. Heap sort is a in place sort.
  2. Time complexity is O(NLogN) for Heapify.A quick look over the above algorithm suggests that the running time is Heap Sort - recursion, since each call to Heapify costs Heap Sort - recursion and Build-Heap makes Heap Sort - recursion such calls.