Skip to content

Create BogoSort.java #275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Sorts/BogoSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*

an implementation of bogosort
input from command line
to increasing order

*/

import java.util.Random;

public class BogoSort {

public static void main(String[] args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++)
arr[i] = Integer.parseInt(args[i]);
while(!isSorted(arr)) arr = scramble(arr);
disp(arr);
}

private static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++)
if (arr[i + 1] < arr[i])
return false;
return true;
}

private static int[] scramble(int[] arr) {
Random rand = new Random();
int[] scr = new int[arr.length], chk = new int[arr.length];
int count = 0, index;
while (count < arr.length) {
index = rand.nextInt(arr.length);
if (chk[index] != 1) {
scr[index] = arr[count];
chk[index] = 1;
count++;
}
}
return scr;
}

private static void disp(int[] arr) {
for(int i : arr) System.out.print(i + " ");
System.out.println();
}
}