Skip to content

Commit 1f7dfb8

Browse files
committedDec 12, 2019
Add BogoSort
1 parent ba2d8dc commit 1f7dfb8

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import Sort from '../Sort';
2+
3+
export default class BogoSort extends Sort {
4+
sort(originalArray) {
5+
// Clone original array to prevent its modification.
6+
let array = [...originalArray];
7+
8+
while (!this.isSorted(array)) { // Verification if is sorted
9+
array = [...this.shuffle(array)]; // Execute shuffle
10+
}
11+
12+
return array;
13+
}
14+
15+
isSorted(array) {
16+
for (let i = 0; i < array.length; i += 1) {
17+
if (array[i - 1] > array[i]) {
18+
return false;
19+
}
20+
}
21+
return true;
22+
}
23+
24+
shuffle(array) {
25+
const newArray = [...array];
26+
let count = array.length;
27+
let index;
28+
let aux;
29+
30+
while (count > 0) {
31+
index = Math.floor(Math.random() * count);
32+
count -= 1;
33+
34+
aux = newArray[count];
35+
newArray[count] = newArray[index];
36+
newArray[index] = aux;
37+
}
38+
39+
return newArray;
40+
}
41+
}

‎src/algorithms/sorting/bogo-sort/README.md

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import BogoSort from '../BogoSort';
2+
import {
3+
equalArr,
4+
notSortedArr,
5+
reverseArr,
6+
sortedArr,
7+
SortTester,
8+
} from '../../SortTester';
9+
10+
const SORTED_ARRAY_VISITING_COUNT = 40;
11+
const NOT_SORTED_ARRAY_VISITING_COUNT = 40;
12+
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 40;
13+
const EQUAL_ARRAY_VISITING_COUNT = 40;
14+
15+
describe('BogoSort', () => {
16+
it('should sort array', () => {
17+
SortTester.testSort(BogoSort);
18+
});
19+
20+
it('should sort array with custom comparator', () => {
21+
SortTester.testSortWithCustomComparator(BogoSort);
22+
});
23+
24+
it('should sort negative numbers', () => {
25+
SortTester.testNegativeNumbersSort(BogoSort);
26+
});
27+
28+
it('should visit EQUAL array element specified number of times', () => {
29+
SortTester.testAlgorithmTimeComplexity(
30+
BogoSort,
31+
equalArr,
32+
EQUAL_ARRAY_VISITING_COUNT,
33+
);
34+
});
35+
36+
it('should visit SORTED array element specified number of times', () => {
37+
SortTester.testAlgorithmTimeComplexity(
38+
BogoSort,
39+
sortedArr,
40+
SORTED_ARRAY_VISITING_COUNT,
41+
);
42+
});
43+
44+
it('should visit NOT SORTED array element specified number of times', () => {
45+
SortTester.testAlgorithmTimeComplexity(
46+
BogoSort,
47+
notSortedArr,
48+
NOT_SORTED_ARRAY_VISITING_COUNT,
49+
);
50+
});
51+
52+
it('should visit REVERSE SORTED array element specified number of times', () => {
53+
SortTester.testAlgorithmTimeComplexity(
54+
BogoSort,
55+
reverseArr,
56+
REVERSE_SORTED_ARRAY_VISITING_COUNT,
57+
);
58+
});
59+
});

0 commit comments

Comments
 (0)
Please sign in to comment.