Skip to content

Instantly share code, notes, and snippets.

@pencil
Last active April 10, 2023 13:57
Show Gist options
  • 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);
}
}
@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