Skip to content

Instantly share code, notes, and snippets.

@alisha
Created February 26, 2013 19:32
Show Gist options
  • Save alisha/5041370 to your computer and use it in GitHub Desktop.
Save alisha/5041370 to your computer and use it in GitHub Desktop.
A program for BogoSort, a method that sorts an array by shuffling it if it is not sorted, and repeats until it is. Used as an example to show why it is important to have an efficient sorting algorithm.
//Alisha Ukani
//github.com/alishau
import java.util.Date;
public class BogoSort {
public static void main(String[] args) {
Date start = new Date(); //Saves time of when the program starts
int[] arr = generateArray(10);
System.out.println("Original array: ");
printArray(arr);
boolean arraySorted = isSorted(arr);
while (!arraySorted) {
arr = shuffleArray(arr);
arraySorted = isSorted(arr);
}
System.out.println("\nSorted array: ");
printArray(arr);
Date end = new Date(); //Saves time of when the program finishes
long timeMillSec = end.getTime() - start.getTime();
double timeSec = timeMillSec/1000;
double timeMin = timeSec/60;
System.out.println("Time it took: " + timeSec + " seconds, or " + timeMin + " minutes.");
}
//Generates an array of randomly generated integers
public static int[] generateArray(int size) {
int[] arr = new int[size];
for (int x = 0; x < size; x++) {
arr[x] = (int)(100 * Math.random());
}
return arr;
}
//Shuffles an array by putting each element into a random spot in a new array
public static int[] shuffleArray(int[] arr) {
Integer[] shuffled = new Integer[arr.length];
boolean isNull = true;
Integer loc = arr.length-1;
int[] updated = new int[arr.length];
for (int x = 0; x < arr.length; x++) {
while (isNull) {
if (shuffled[loc] == null) { //If a random element in shuffled is null, put this value in that spot
shuffled[loc] = new Integer(arr[x]);
isNull = false;
updated[loc] = arr[x];
break;
}
loc = new Integer((int)(10*Math.random()));
}
isNull = true;
}
return updated;
}
//Swaps two elements in an array
public static int[] swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
return arr;
}
//Checks to see if the array is sorted in ascending order
public static boolean isSorted(int[] arr) {
boolean sorted = true;
for (int x = 0; x < arr.length - 1; x++) {
if (arr[x] > arr[x+1]) {
sorted = false;
}
}
return sorted;
}
//Prints the array
public static void printArray(int[] arr) {
for (int g = 0; g < arr.length; g++) {
System.out.print(arr[g]);
if (g != arr.length - 1) {
System.out.print(", ");
} else {
System.out.println("");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment