Last active
October 12, 2015 19:08
-
-
Save mtimkovich/4074201 to your computer and use it in GitHub Desktop.
The Campbell Sorting Algorithm
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 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