Skip to content

Instantly share code, notes, and snippets.

@mtimkovich
Last active October 12, 2015 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtimkovich/4074201 to your computer and use it in GitHub Desktop.
Save mtimkovich/4074201 to your computer and use it in GitHub Desktop.
The Campbell Sorting Algorithm
public class Paul {
public static void printArray(int[] array) {
System.out.print("{");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1) {
System.out.print(", ");
}
}
System.out.println("}");
}
public static boolean isSorted(int[] array) {
boolean sorted = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i+1]) {
sorted = false;
}
}
return sorted;
}
public static void randomizeArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int randomIndex = (int) (Math.random() * (array.length - 1 - i) + 1);
int swap = array[i];
array[i] = array[randomIndex];
array[randomIndex] = swap;
}
}
public static void campbellSort(int[] array) {
int tries = 0;
while (! isSorted(array)) {
randomizeArray(array);
tries++;
}
System.out.println("tries: " + tries);
}
public static void main(String[] args) {
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
printArray(array);
campbellSort(array);
printArray(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment