From 792621e67fdd2f15d64402b93a30ef14d46edf02 Mon Sep 17 00:00:00 2001 From: Lucas Lemaire Date: Wed, 7 Oct 2015 08:48:58 +0200 Subject: [PATCH] Add ShellSort with test --- Algorithms/Sorting/ShellSorter.cs | 58 ++++++++++++++++++++ MainProgram/AlgorithmsTests/ShellSortTest.cs | 32 +++++++++++ 2 files changed, 90 insertions(+) create mode 100644 Algorithms/Sorting/ShellSorter.cs create mode 100644 MainProgram/AlgorithmsTests/ShellSortTest.cs diff --git a/Algorithms/Sorting/ShellSorter.cs b/Algorithms/Sorting/ShellSorter.cs new file mode 100644 index 00000000..3a78dd04 --- /dev/null +++ b/Algorithms/Sorting/ShellSorter.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using Algorithms.Common; + +namespace Algorithms.Sorting +{ + public static class ShellSorter + { + public static void BubbleSort(this IList collection, Comparer comparer = null) + { + comparer = comparer ?? Comparer.Default; + collection.ShellSortAscending(comparer); + } + + /// + /// Public API: Sorts ascending + /// + public static void ShellSortAscending(this IList collection, Comparer 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; + } + } + } + } + + /// + /// Public API: Sorts descending + /// + public static void ShellSortDescending(this IList collection, Comparer 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; + } + } + } + } + } +} diff --git a/MainProgram/AlgorithmsTests/ShellSortTest.cs b/MainProgram/AlgorithmsTests/ShellSortTest.cs new file mode 100644 index 00000000..276d7a9f --- /dev/null +++ b/MainProgram/AlgorithmsTests/ShellSortTest.cs @@ -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 numbers = new List { 54, 26, 93, 17, 77, 31, 44, 55, 20 }; + numbers.ShellSortAscending(Comparer.Default); + + Debug.Assert(numbers.SequenceEqual(numbers.OrderBy(i => i)), "Wrong SelectionSort ascending"); + } + + public static void DoTestDescending() + { + List numbers = new List {84,69,76,86,94,91 }; + numbers.ShellSortDescending(Comparer.Default); + + Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong SelectionSort descending"); + } + } +}