Skip to content

Instantly share code, notes, and snippets.

@connlark
Created February 19, 2016 16:14
Show Gist options
  • Save connlark/4b7937b699bd1a93a78f to your computer and use it in GitHub Desktop.
Save connlark/4b7937b699bd1a93a78f to your computer and use it in GitHub Desktop.
cheeky as fuck
import java.text.NumberFormat;
import java.util.Arrays;
public class BogoSort
{
//Enter array to be sorted here
static int[] arr={1,2,3,4,5,6,7,8,9,10,11,12};
static int[] sortedArr = new int[arr.length];
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
sortedArr = arr.clone();
Arrays.sort(sortedArr);
BogoSort now=new BogoSort();
System.out.print("Unsorted: ");
now.display1D(arr);
System.out.println("Elements: " + arr.length);
now.bogo(arr);
System.out.print("Sorted: ");
now.display1D(arr);
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Total runtime(ms): " + NumberFormat.getInstance().format(totalTime));
}
void bogo(int[] arr)
{
shuffle(arr);
//Keep a track of the number of shuffles
int shuffle=1;
for(;!isSorted(arr);shuffle++)
shuffle(arr);
//Boast
System.out.println("This took "+ NumberFormat.getInstance().format(shuffle)+" shuffles.");
}
public void shuffle(int[] arr)
{
//Standard Fisher-Yates shuffle algorithm
int i=arr.length-1;
while(i>0)
swap(arr,i--,(int)(Math.random()*i));
}
void swap(int[] arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
boolean isSorted(int[] arr)
{
return Arrays.equals(arr, sortedArr);
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment