Skip to content

Commit e3eff33

Browse files
author
Christian Bender
committed
added bogo sort
1 parent c881983 commit e3eff33

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

src/sorting.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
module.exports = {
22
bubbleSort: require('./sorting/bubble-sort'),
3-
mergeSort: require('./sorting/merge-sort')
3+
mergeSort: require('./sorting/merge-sort'),
4+
bogoSort: require('./sorting/bogo-sort')
45
};

src/sorting/bogo-sort.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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;

src/test/sorting.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,7 @@ test('Testing Bubble Sort', t => {
1212
test('Testing Merge Sort', t => {
1313
t.deepEqual(expected, sorting.mergeSort(array));
1414
});
15+
16+
test('Testing Bogo Sort', t => {
17+
t.deepEqual(expected, sorting.bogoSort(array));
18+
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy