Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# pencil/RandomSort.java

Last active Nov 12, 2020
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 commented Nov 29, 2018

 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.
to join this conversation on GitHub. Already have an account? Sign in to comment