License Public Domain
Lines 39
Keywords
BogoSort (3) C# (7) .Net (8)
Included in this Library
Implements this Algorithm
Permissions
Group Owner: .Net
Viewable by Everyone
Editable by Spencer Ruport
Hide
Need a quick chart or graph for your blog? Try our reStructured Text renderer. Join Siafoo Now or Learn More

BogoSort C# Atom Feed 0

In Brief Just for fun. Only time I'd recommend using it is if you're trying to convince someone it's time to upgrade a box. :o... more
# 's
 1class BogoSort
2{
3 private static Random rnd;
4
5 public static int Sort(object[] array)
6 {
7 int count = 0;
8
9 while (!isSorted(array))
10 {
11 Shuffle(array);
12 count++;
13 }
14
15 return count;
16 }
17
18 public static void Shuffle(object[] array)
19 {
20 if (rnd == null) rnd = new Random();
21
22 for (int i = 0; i < array.Length; i++)
23 Swap(array, i, rnd.Next(0, array.Length - 1));
24 }
25
26 private static void Swap(object[] array, int item1, int item2)
27 {
28 object temp = array[item1];
29 array[item1] = array[item2];
30 array[item2] = temp;
31 }
32
33 private static bool isSorted(object[] array)
34 {
35 bool ret = true;
36
37 for (int i = 0; i < array.Length - 1; i++)
38 {
39 if (((IComparable)array[i]).CompareTo(((IComparable)array[i+1])) == 1)
40 {
41 ret = false;
42 break;
43 }
44 }
45
46 return ret;
47 }
48}

Just for fun. Only time I'd recommend using it is if you're trying to convince someone it's time to upgrade a box. :o

Tried using it with 12 strings and landed a sorted result after 318,496,543 shuffles and just shy of five minutes.