public
Last active

Random Sort (bogosort, stupid sort) implementation in Java

  • Download Gist
RandomSort.java
Java
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
public class RandomSort {
 
public RandomSort(int[] i) {
int counter = 0;
System.out.println("I'll sort " + i.length + " elements...");
while (!isSorted(i)) {
shuffle(i);
counter++;
}
System.out.println("Solution found! (shuffled " + counter + " times)");
print(i);
}
 
private void print(int[] i) {
for (int x : i) {
System.out.print(x + ", ");
}
System.out.println();
}
 
private void shuffle(int[] i) {
for (int x = 0; x < i.length; ++x) {
int index1 = (int) (Math.random() * i.length), index2 = (int) (Math
.random() * i.length);
int a = i[index1];
i[index1] = i[index2];
i[index2] = a;
}
}
 
private boolean isSorted(int[] i) {
for (int x = 0; x < i.length - 1; ++x) {
if (i[x] > i[x + 1]) {
return false;
}
}
return true;
}
 
public static void main(String[] args) {
int[] i = { 1, 5, 2, 8, 5, 2, 4, 2, 6, 7, 66 };
new RandomSort(i);
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.