forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSorter.cs
68 lines (58 loc) · 2.12 KB
/
HeapSorter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison
{
/// <summary>
/// Heap sort is a comparison based sorting technique
/// based on Binary Heap data structure.
/// </summary>
/// <typeparam name="T">Input array type.</typeparam>
public class HeapSorter<T> : IComparisonSorter<T>
{
/// <summary>
/// Sorts input array using heap sort algorithm.
/// </summary>
/// <param name="array">Input array.</param>
/// <param name="comparer">Comparer type for elements.</param>
public void Sort(T[] array, IComparer<T> comparer) => HeapSort(array, comparer);
private static void HeapSort(IList<T> data, IComparer<T> comparer)
{
var heapSize = data.Count;
for (var p = (heapSize - 1) / 2; p >= 0; p--)
{
MakeHeap(data, heapSize, p, comparer);
}
for (var i = data.Count - 1; i > 0; i--)
{
var temp = data[i];
data[i] = data[0];
data[0] = temp;
heapSize--;
MakeHeap(data, heapSize, 0, comparer);
}
}
private static void MakeHeap(IList<T> input, int heapSize, int index, IComparer<T> comparer)
{
var rIndex = index;
while (true)
{
var left = (rIndex + 1) * 2 - 1;
var right = (rIndex + 1) * 2;
var largest = left < heapSize && comparer.Compare(input[left], input[rIndex]) == 1 ? left : rIndex;
// finds the index of the largest
if (right < heapSize && comparer.Compare(input[right], input[largest]) == 1)
{
largest = right;
}
if (largest == rIndex)
{
return;
}
// process of reheaping / swapping
var temp = input[rIndex];
input[rIndex] = input[largest];
input[largest] = temp;
rIndex = largest;
}
}
}
}