Last active
February 13, 2025 19:31
-
-
Save pencil/1253001 to your computer and use it in GitHub Desktop.
Random Sort (bogosort, stupid sort) implementation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have convinced me to use this.