forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BogoSorter.cs
63 lines (56 loc) · 1.65 KB
/
BogoSorter.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
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison
{
/// <summary>
/// Class that implements bogo sort algorithm.
/// </summary>
/// <typeparam name="T">Type of array element.</typeparam>
public class BogoSorter<T> : IComparisonSorter<T>
{
private readonly Random random = new Random();
/// <summary>
/// TODO.
/// </summary>
/// <param name="array">TODO. 2.</param>
/// <param name="comparer">TODO. 3.</param>
public void Sort(T[] array, IComparer<T> comparer)
{
while (!IsSorted(array, comparer))
{
Shuffle(array);
}
}
private bool IsSorted(T[] array, IComparer<T> comparer)
{
for (var i = 0; i < array.Length - 1; i++)
{
if (comparer.Compare(array[i], array[i + 1]) > 0)
{
return false;
}
}
return true;
}
private void Shuffle(T[] array)
{
var taken = new bool[array.Length];
var newArray = new T[array.Length];
for (var i = 0; i < array.Length; i++)
{
int nextPos;
do
{
nextPos = random.Next(0, int.MaxValue) % array.Length;
}
while (taken[nextPos]);
taken[nextPos] = true;
newArray[nextPos] = array[i];
}
for (var i = 0; i < array.Length; i++)
{
array[i] = newArray[i];
}
}
}
}