Generic Heap sort - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Sort

Description

Generic Heap sort

Demo Code


using System.Security;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;

public class Main{
    private static void Heapsort(T[] keys, int lo, int hi, IComparer<T> comparer)
    {/*from  w w  w  .j a v  a  2s .  c  om*/
      int n = hi - lo + 1;
      for (int i = n / 2; i >= 1; --i)
        ArraySortHelper<T>.DownHeap(keys, i, n, lo, comparer);
      for (int index = n; index > 1; --index)
      {
        T[] a = keys;
        int i = lo;
        int num = index;
        int j = i + num - 1;
        Swap(a, i, j);
        DownHeap(keys, 1, index - 1, lo, comparer);
      }
    }
    private static void Swap(T[] a, int i, int j)
    {
      if (i == j)
        return;
      T obj = a[i];
      a[i] = a[j];
      a[j] = obj;
    }
    private static void DownHeap(T[] keys, int i, int n, int lo, IComparer<T> comparer)
    {
      T x = keys[lo + i - 1];
      int num;
      for (; i <= n / 2; i = num)
      {
        num = 2 * i;
        if (num < n && comparer.Compare(keys[lo + num - 1], keys[lo + num]) < 0)
          ++num;
        if (comparer.Compare(x, keys[lo + num - 1]) < 0)
          keys[lo + i - 1] = keys[lo + num - 1];
        else
          break;
      }
      keys[lo + i - 1] = x;
    }
}

Related Tutorials