Skip to content

Instantly share code, notes, and snippets.

@pencil
Last active April 10, 2023 13:57
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pencil/1253001 to your computer and use it in GitHub Desktop.
Save pencil/1253001 to your computer and use it in GitHub Desktop.
Random Sort (bogosort, stupid sort) implementation in Java
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);
}
}
@jodyrutter
Copy link

Thank you. This algorithm is super efficient. Why do I still use crappy algorithms like merge sort and quick sort? I could be using this brilliant algorithm designed by the great Albert Einstein himself instead. I wish you luck in your endeavors. Remember to continue sorting in O((n+1)!) time. n log n is sooo overrated.

@hueychen27
Copy link

You have convinced me to use this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment