File tree Expand file tree Collapse file tree 3 files changed +49
-1
lines changed Expand file tree Collapse file tree 3 files changed +49
-1
lines changed Original file line number Diff line number Diff line change 1
1
module . exports = {
2
2
bubbleSort : require ( './sorting/bubble-sort' ) ,
3
- mergeSort : require ( './sorting/merge-sort' )
3
+ mergeSort : require ( './sorting/merge-sort' ) ,
4
+ bogoSort : require ( './sorting/bogo-sort' )
4
5
} ;
Original file line number Diff line number Diff line change
1
+ const Comparator = require ( '../util/comparator' ) ;
2
+
3
+ /* HELPER-FUNCTION
4
+ isSort : checks whether the given array is sorted (ascending)
5
+ returns true if the given array is ascending sorted otherwise false
6
+ */
7
+ const isSorted = ( a , comparator ) => {
8
+ for ( let i = 0 ; i < a . size - 1 ; i ++ ) {
9
+ if ( comparator . greaterThan ( a [ i ] , a [ i + 1 ] ) )
10
+ return false ;
11
+ }
12
+ return true ;
13
+ } ;
14
+
15
+ /*
16
+ HELPER-FUNCTION
17
+ randInt : returns a random integer between 0 and N-1
18
+ */
19
+ const randInt = ( N ) => {
20
+ return Math . floor ( Math . random ( ) * N ) ;
21
+ } ;
22
+
23
+ /*
24
+ bogoSort: bogo-sort (stupid-sort) algorithm for a given array 'a'
25
+ */
26
+ const bogoSort = ( arr , compareFunction ) => {
27
+ const comparator = new Comparator ( compareFunction ) ;
28
+
29
+ while ( ! isSorted ( arr ) ) {
30
+ let a = randInt ( arr . size ) ;
31
+ let b = randInt ( arr . size ) ;
32
+
33
+ let tmp = arr [ a ] ;
34
+ arr [ a ] = arr [ b ] ;
35
+ arr [ b ] = tmp ;
36
+
37
+ }
38
+
39
+ return arr ;
40
+
41
+ } ;
42
+
43
+ module . exports = bogoSort ;
Original file line number Diff line number Diff line change @@ -12,3 +12,7 @@ test('Testing Bubble Sort', t => {
12
12
test ( 'Testing Merge Sort' , t => {
13
13
t . deepEqual ( expected , sorting . mergeSort ( array ) ) ;
14
14
} ) ;
15
+
16
+ test ( 'Testing Bogo Sort' , t => {
17
+ t . deepEqual ( expected , sorting . bogoSort ( array ) ) ;
18
+ } ) ;
You can’t perform that action at this time.
0 commit comments