Skip to content

Commit defa33d

Browse files
authored
Add Timsort (TheAlgorithms#267)
1 parent 73c89d8 commit defa33d

File tree

3 files changed

+705
-0
lines changed

3 files changed

+705
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
using System;
2+
using System.Linq;
3+
using Algorithms.Sorters.Comparison;
4+
using Algorithms.Tests.Helpers;
5+
using NUnit.Framework;
6+
7+
namespace Algorithms.Tests.Sorters.Comparison
8+
{
9+
public static class TimSorterTests
10+
{
11+
private static readonly IntComparer IntComparer = new();
12+
13+
[Test]
14+
public static void ArraySorted(
15+
[Random(0, 1000, 100, Distinct = true)]
16+
int n)
17+
{
18+
// Arrange
19+
var sorter = new TimSorter<int>();
20+
var (correctArray, testArray) = RandomHelper.GetArrays(n);
21+
22+
// Act
23+
sorter.Sort(testArray, IntComparer);
24+
Array.Sort(correctArray, IntComparer);
25+
26+
// Assert
27+
Assert.AreEqual(testArray, correctArray);
28+
}
29+
30+
[Test]
31+
public static void TinyArray()
32+
{
33+
// Arrange
34+
var sorter = new TimSorter<int>();
35+
var tinyArray = new[] { 1 };
36+
var correctArray = new[] { 1 };
37+
38+
// Act
39+
sorter.Sort(tinyArray, IntComparer);
40+
41+
// Assert
42+
Assert.AreEqual(tinyArray, correctArray);
43+
}
44+
45+
[Test]
46+
public static void SmallChunks()
47+
{
48+
// Arrange
49+
var sorter = new TimSorter<int>();
50+
var (correctArray, testArray) = RandomHelper.GetArrays(800);
51+
Array.Sort(correctArray, IntComparer);
52+
Array.Sort(testArray, IntComparer);
53+
54+
var max = testArray.Max();
55+
var min = testArray.Min();
56+
57+
correctArray[0] = max;
58+
correctArray[800-1] = min;
59+
testArray[0] = max;
60+
testArray[800 - 1] = min;
61+
62+
// Act
63+
sorter.Sort(testArray, IntComparer);
64+
Array.Sort(correctArray, IntComparer);
65+
66+
// Assert
67+
Assert.AreEqual(testArray, correctArray);
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)