-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBogoSort.java
More file actions
73 lines (59 loc) · 1.86 KB
/
BogoSort.java
File metadata and controls
73 lines (59 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.pslin.algorithms.sort;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Random;
/**
* While not sorted, shuffle array.
*
* @author plin
*/
public class BogoSort {
public static void main(String[] args) {
int length;
if(args.length == 0) {
length = 12;
} else {
length = Integer.parseInt(args[0]);
}
int[] numbers = createArray(length);
shuffle(numbers);
System.out.println(Arrays.toString(numbers));
long count = 0;
double start = System.currentTimeMillis();
while(!isSorted(numbers)) {
shuffle(numbers);
count++;
}
System.out.println("\n" + Arrays.toString(numbers));
DecimalFormat decimalFormat = new DecimalFormat("#,###");
System.out.println("Number of shuffles: " + decimalFormat.format(count));
double time = System.currentTimeMillis() - start;
System.out.println("Time: " + time + " ms");
System.out.println(time / 1000 + " sec");
}
private static int[] createArray(int length) {
int[] numbers = new int[length];
for(int i=0; i < numbers.length; i++) {
numbers[i] = i;
}
return numbers;
}
private static void shuffle(int[] numbers) {
Random rnd = new Random();
for (int i = numbers.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
int a = numbers[index];
numbers[index] = numbers[i];
numbers[i] = a;
}
}
private static boolean isSorted(int[] numbers) {
for(int i=0; i < numbers.length-1; i++) {
if(numbers[i] > numbers[i+1]) {
return false;
}
}
return true;
}
}