Skip to content

Commit

Permalink
Add ShellSort with test
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Lemaire committed Oct 7, 2015
1 parent 4bd494e commit 792621e
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
58 changes: 58 additions & 0 deletions Algorithms/Sorting/ShellSorter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System.Collections.Generic;
using Algorithms.Common;

namespace Algorithms.Sorting
{
public static class ShellSorter
{
public static void BubbleSort<T>(this IList<T> collection, Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
collection.ShellSortAscending(comparer);
}

/// <summary>
/// Public API: Sorts ascending
/// </summary>
public static void ShellSortAscending<T>(this IList<T> collection, Comparer<T> comparer)
{
bool flag = true;
int d = collection.Count;
while (flag || (d > 1))
{
flag = false;
d = (d + 1) / 2;
for (int i = 0; i < (collection.Count - d); i++)
{
if (comparer.Compare(collection[i + d], collection[i]) < 0)
{
collection.Swap(i + d, i);
flag = true;
}
}
}
}

/// <summary>
/// Public API: Sorts descending
/// </summary>
public static void ShellSortDescending<T>(this IList<T> collection, Comparer<T> comparer)
{
bool flag = true;
int d = collection.Count;
while (flag || (d > 1))
{
flag = false;
d = (d + 1) / 2;
for (int i = 0; i < (collection.Count - d); i++)
{
if (comparer.Compare(collection[i + d], collection[i])>0)
{
collection.Swap(i+d,i);
flag = true;
}
}
}
}
}
}
32 changes: 32 additions & 0 deletions MainProgram/AlgorithmsTests/ShellSortTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Algorithms.Sorting;

namespace C_Sharp_Algorithms.AlgorithmsTests
{
public static class ShellSortTest
{
public static void DoTest()
{
DoTestAscending();
DoTestDescending();
}

public static void DoTestAscending()
{
List<int> numbers = new List<int> { 54, 26, 93, 17, 77, 31, 44, 55, 20 };
numbers.ShellSortAscending(Comparer<int>.Default);

Debug.Assert(numbers.SequenceEqual(numbers.OrderBy(i => i)), "Wrong SelectionSort ascending");
}

public static void DoTestDescending()
{
List<int> numbers = new List<int> {84,69,76,86,94,91 };
numbers.ShellSortDescending(Comparer<int>.Default);

Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong SelectionSort descending");
}
}
}

0 comments on commit 792621e

Please sign in to comment.