1. package shitty.bogo;
  2. import java.util.*;
  3. public class sorter {
  4. public static void main(String[] args) {
  5. long count = 0;
  6. System.out.println("How many elements would you like to sort?");
  7. Scanner in = new Scanner(System.in);
  8. int elnum = in.nextInt();
  9. int[] elements = new int[elnum];
  10. for(int c = 0; c < elements.length; c++)
  11. elements[c] = c;
  12. do{
  13. shuffleArray(elements);
  14. System.out.print(count + ": ");
  15. for (int c = 0; c < elements.length; c++)
  16. System.out.print(elements[c] + " ");
  17. System.out.println("");
  18. count++;
  19. } while(isSorted(elements) == false);
  20. System.out.println( "List is sorted above in " + count + " tries!");
  21. main(args);
  22. in.close();
  23. }
  24. public static void shuffleArray(int[] ar){
  25. Random rnd = new Random();
  26. for (int i = ar.length - 1; i > 0; i--){
  27. int index = rnd.nextInt(i + 1);
  28. int a = ar[index];
  29. ar[index] = ar[i];
  30. ar[i] = a;
  31. }
  32. }
  33. public static boolean isSorted(int[] e){
  34. for(int c = 0; c < e.length -1; c++){
  35. if(e[c] > e[c+1])
  36. return false;
  37. }
  38. return true;
  39. }
  40. }

So, I made this out of inspiration for some of the students in a lower level CS class. They were talking about sorting algorithms and wanted to know one that could work in the best possible time. Introduce bogo sort! While it relies on this nasty thing called probability and its Worse case is O(forever), it 'could' solve it on the first try. Enjoy.

If you want it to go faster, comment out the print statements in the while loop.

Example of output, number entered being ten.

5616773: 2 1 4 5 6 3 7 8 9 0

5616774: 9 5 6 2 4 1 3 8 0 7

5616775: 8 2 5 1 9 3 7 4 6 0

5616776: 6 7 0 2 1 5 3 4 8 9

5616777: 3 1 5 8 6 4 9 0 7 2

5616778: 5 6 7 8 2 1 3 4 0 9

5616779: 0 1 2 3 4 5 6 7 8 9

List is sorted above in 5616780 tries!