-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
CombSorter.cs
51 lines (46 loc) · 1.61 KB
/
CombSorter.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
using System;
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison;
/// <summary>
/// Comb sort is a relatively simple sorting algorithm that improves on bubble sort.
/// </summary>
/// <typeparam name="T">Type of array element.</typeparam>
public class CombSorter<T> : IComparisonSorter<T>
{
public CombSorter(double shrinkFactor = 1.3) => ShrinkFactor = shrinkFactor;
private double ShrinkFactor { get; }
/// <summary>
/// Sorts array using specified comparer,
/// internal, in-place, unstable,
/// worst case performance: O(n^2),
/// best case performance: O(n log(n)),
/// average performance: O(n^2 / 2^p),
/// space complexity: O(1),
/// where n - array length and p - number of increments.
/// See <a href="https://en.wikipedia.org/wiki/Comb_sort">here</a> for more info.
/// </summary>
/// <param name="array">Array to sort.</param>
/// <param name="comparer">Compares elements.</param>
public void Sort(T[] array, IComparer<T> comparer)
{
var gap = array.Length;
var sorted = false;
while (!sorted)
{
gap = (int)Math.Floor(gap / ShrinkFactor);
if (gap <= 1)
{
gap = 1;
sorted = true;
}
for (var i = 0; i < array.Length - gap; i++)
{
if (comparer.Compare(array[i], array[i + gap]) > 0)
{
(array[i], array[i + gap]) = (array[i + gap], array[i]);
sorted = false;
}
}
}
}
}