1
1
/*
2
- *
3
2
* @author Marcelo Wischniowski <marcelowisc at gmail.com>
4
3
*/
5
4
public class BogoSort {
6
5
7
- /**
8
- * @param vector
9
- */
10
- public int [] sort (int [] vector ) {
11
- // Checking if the vector is ordered
6
+ public static int [] bogoSort (int [] vector ) {
7
+ // Check if the vector is ordered
12
8
while (!isSorted (vector )) {
13
9
// Shuffle the vector to try to sort it randomly
14
10
shuffle (vector );
@@ -17,10 +13,7 @@ public int[] sort(int[] vector) {
17
13
}
18
14
19
15
/**
20
- * Checking again if the vector is ordered
21
- *
22
- * @param vector
23
- * @return
16
+ * Check if the vector is ordered
24
17
*/
25
18
private static boolean isSorted (int [] vector ) {
26
19
for (int i = 0 ; i < (vector .length - 1 ); ++i ) {
@@ -34,8 +27,6 @@ private static boolean isSorted(int[] vector) {
34
27
35
28
/**
36
29
* Shuffle the vector to try to sort it randomly
37
- *
38
- * @param vector Vector is to be sorted
39
30
*/
40
31
private static void shuffle (int [] vector ) {
41
32
for (int x = 0 ; x < vector .length ; ++x ) {
@@ -46,53 +37,25 @@ private static void shuffle(int[] vector) {
46
37
vector [index2 ] = a ;
47
38
}
48
39
}
49
- }
50
- /*
51
- *
52
- * @author Marcelo Wischniowski <marcelowisc at gmail.com>
53
- */
54
- public class BogoSort {
55
40
56
- /**
57
- * @param vector
58
- */
59
- public int [] sort (int [] vector ) {
60
- // Verify if the vector is ordered
61
- while (!isSorted (vector )) {
62
- // Shuffle the vector to try to sort it randomly
63
- shuffle (vector );
41
+ public static void printVector (int vector []) {
42
+ for (int i = 0 ; i < vector .length ; i ++) {
43
+ System .out .print (vector [i ] + ", " );
64
44
}
65
- return vector ;
45
+ System . out . println ( "" ) ;
66
46
}
67
47
68
- /**
69
- * Verify if the vector (named vector) is sorted
70
- *
71
- * @param vector
72
- * @return
73
- */
74
- private static boolean isSorted (int [] vector ) {
75
- for (int i = 0 ; i < (vector .length - 1 ); ++i ) {
76
- if (vector [i ] > vector [i + 1 ]) {
77
- return false ;
78
- }
79
- }
48
+ public static void main (String [] args ) {
80
49
81
- return true ;
82
- }
50
+ int vector [] = {9 , 0 , 4 , 2 , 3 , 8 , 7 , 1 , 6 , 5 };
83
51
84
- /**
85
- * Shuffle the vector to try to sort it randomly
86
- *
87
- * @param vector Vector is to be sorted
88
- */
89
- private static void shuffle (int [] vector ) {
90
- for (int x = 0 ; x < vector .length ; ++x ) {
91
- int index1 = (int ) (Math .random () * vector .length ),
92
- index2 = (int ) (Math .random () * vector .length );
93
- int a = vector [index1 ];
94
- vector [index1 ] = vector [index2 ];
95
- vector [index2 ] = a ;
96
- }
52
+ System .out .println ("BogoSort:" );
53
+ System .out .println ("Unordered vector:" );
54
+ printVector (vector );
55
+
56
+ vector = bogoSort (vector );
57
+
58
+ System .out .println ("Sorted vector:" );
59
+ printVector (vector );
97
60
}
98
61
}
0 commit comments