Skip to content
Snippets Groups Projects
Commit abdef015 authored by Dmytro Bogatov's avatar Dmytro Bogatov :two_hearts:
Browse files

Cahnges overview:

Add HeapSort.
parent f6fb6e53
Branches
No related tags found
No related merge requests found
......@@ -36,6 +36,7 @@
<Compile Include="Sort\SelectionSortTests.cs" />
<Compile Include="Sort\MergeSortTests.cs" />
<Compile Include="Sort\QuickSortTests.cs" />
<Compile Include="Sort\HeapSortTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
......
//
//
// This file - HeapSortTests.cs was created by Dmytro Bogatov (dmytro@dbogatov.org)
// on 12/7/2016, 2:47 PM
using System;
using System.Linq;
using NUnit.Framework;
namespace Sort
{
[TestFixture]
public class HeapSortTests
{
[Test]
public void TestCases()
{
Assert.AreEqual(
new int[] { -1, 1, 2, 5, 8, 9, 45 },
HeapSort.Sort(new int[] { 5, 2, 1, -1, 8, 45, 9 })
);
Assert.AreEqual(
new int[] { 2, 5, 6, 8, 9 },
HeapSort.Sort(new int[] { 5, 2, 6, 8, 9 })
);
Assert.AreEqual(
new int[] { 1 },
HeapSort.Sort(new int[] { 1 })
);
Assert.AreEqual(
new int[] { },
HeapSort.Sort(new int[] { })
);
Assert.AreEqual(
new int[] { 5, 5, 6 },
HeapSort.Sort(new int[] { 5, 6, 5 })
);
Random randNum = new Random();
var list = Enumerable.Repeat(0, 25).Select(i => randNum.Next(-100, 100)).ToList();
var input = list.ToArray();
list.Sort();
var expected = list.ToArray();
Assert.AreEqual(
expected,
HeapSort.Sort(input)
);
}
}
}
......@@ -36,6 +36,7 @@
<Compile Include="Sort\SelectionSort.cs" />
<Compile Include="Sort\MergeSort.cs" />
<Compile Include="Sort\QuickSort.cs" />
<Compile Include="Sort\HeapSort.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Sort\" />
......
//
//
// This file - HeapSort.cs was created by Dmytro Bogatov (dmytro@dbogatov.org)
// on 12/7/2016, 2:44 PM
namespace Sort
{
// Mostly borrowed from https://begeeben.wordpress.com/2012/08/21/heap-sort-in-c/
public class HeapSort
{
public static int[] Sort(int[] input)
{
if (input.Length < 2)
{
return input;
}
//Build-Max-Heap
int heapSize = input.Length;
for (int p = (heapSize - 1) / 2; p >= 0; p--)
MaxHeapify(input, heapSize, p);
for (int i = input.Length - 1; i > 0; i--)
{
//Swap
int temp = input[i];
input[i] = input[0];
input[0] = temp;
heapSize--;
MaxHeapify(input, heapSize, 0);
}
return input;
}
static void MaxHeapify(int[] input, int heapSize, int index)
{
int left = (index + 1) * 2 - 1;
int right = (index + 1) * 2;
int largest = 0;
if (left < heapSize && input[left] > input[index])
largest = left;
else
largest = index;
if (right < heapSize && input[right] > input[largest])
largest = right;
if (largest != index)
{
int temp = input[index];
input[index] = input[largest];
input[largest] = temp;
MaxHeapify(input, heapSize, largest);
}
}
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment