Skip to content

Commit 906dfaa

Browse files
authored
Add Exchange Sort (TheAlgorithms#301)
1 parent b665fc2 commit 906dfaa

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using Algorithms.Sorters.Comparison;
3+
using Algorithms.Tests.Helpers;
4+
using NUnit.Framework;
5+
6+
namespace Algorithms.Tests.Sorters.Comparison
7+
{
8+
public static class ExchangeSorterTests
9+
{
10+
[Test]
11+
public static void ArraySorted(
12+
[Random(0, 1000, 100, Distinct = true)]
13+
int n)
14+
{
15+
// Arrange
16+
var sorter = new ExchangeSorter<int>();
17+
var intComparer = new IntComparer();
18+
var (correctArray, testArray) = RandomHelper.GetArrays(n);
19+
20+
// Act
21+
sorter.Sort(testArray, intComparer);
22+
Array.Sort(correctArray, intComparer);
23+
24+
// Assert
25+
Assert.AreEqual(testArray, correctArray);
26+
}
27+
}
28+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using System.Collections.Generic;
2+
3+
namespace Algorithms.Sorters.Comparison
4+
{
5+
/// <summary>
6+
/// Class that implements exchange sort algorithm.
7+
/// </summary>
8+
/// <typeparam name="T">Type of array element.</typeparam>
9+
public class ExchangeSorter<T> : IComparisonSorter<T>
10+
{
11+
/// <summary>
12+
/// Sorts array using specified comparer,
13+
/// internal, in-place, stable,
14+
/// time complexity: O(n^2),
15+
/// space complexity: O(1),
16+
/// where n - array length.
17+
/// </summary>
18+
/// <param name="array">Array to sort.</param>
19+
/// <param name="comparer">Compares elements.</param>
20+
public void Sort(T[] array, IComparer<T> comparer)
21+
{
22+
for (var i = 0; i < array.Length - 1; i++)
23+
{
24+
for (var j = i + 1; j < array.Length; j++)
25+
{
26+
if (comparer.Compare(array[i], array[j]) > 0)
27+
{
28+
(array[j], array[i]) = (array[i], array[j]);
29+
}
30+
}
31+
}
32+
}
33+
}
34+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ This repository contains algorithms and data structures implemented in C# for ed
7171
* [Cocktail Sort](./Algorithms/Sorters/Comparison/CocktailSorter.cs)
7272
* [Comb Sort](./Algorithms/Sorters/Comparison/CombSorter.cs)
7373
* [Cycle Sort](./Algorithms/Sorters/Comparison/CycleSorter.cs)
74+
* [Exchange Sort](./Algorithms/Sorters/Comparison/ExchangeSorter.cs)
7475
* [Heap Sort](./Algorithms/Sorters/Comparison/HeapSorter.cs)
7576
* [Insertion Sort](./Algorithms/Sorters/Comparison/InsertionSorter.cs)
7677
* [Merge Sort](./Algorithms/Sorters/Comparison/MergeSorter.cs)

0 commit comments

Comments
 (0)