Skip to content

Instantly share code, notes, and snippets.

@dadhi
Created January 9, 2024 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadhi/1b6fe3a302cf306f8d4094d614c35abc to your computer and use it in GitHub Desktop.
Save dadhi/1b6fe3a302cf306f8d4094d614c35abc to your computer and use it in GitHub Desktop.
Heap sort of string in place instead of insertion sort
// https://www.hackertouch.com/csharp-generic-heap-sort.html
using System;
public static class HeapSortMethods
{
public static void HeapSort(string[] a)
{
// build binary heap from all items
for (int i = 0; i < a.Length; i++)
{
int index = i;
var s = a[i]; // use next item
// and move it on top, if greater than parent
while (index > 0 && a[(index - 1) / 2].CompareTo(s) < 0)
{
int top = (index - 1) / 2;
a[index] = a[top];
index = top;
}
a[index] = s;
}
for (int i = a.Length - 1; i > 0; i--)
{
// delete max and place it as last
var last = a[i];
a[i] = a[0];
int index = 0;
// the last one positioned in the heap
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
if (right < i && a[left].CompareTo(a[right]) < 0)
{
if (last.CompareTo(a[right]) > 0)
break;
a[index] = a[right];
index = right;
}
else
{
if (last.CompareTo(a[left]) > 0)
break;
a[index] = a[left];
index = left;
}
}
a[index] = last;
}
}
}
public class Program
{
public static void Main()
{
string[] testList = { "US", "UK", "JPN", "CAN", "PAK", "IND" };
HeapSortMethods.HeapSort(testList);
foreach (var t in testList)
{
Console.WriteLine(t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment