Compare commits

...

2 Commits

Author SHA1 Message Date
Antonio Eduardo Moreira
7c48d29a19
Merge 1f7dfb875c into 2c67b48c21 2024-04-25 08:18:33 +08:00
edumoreira1506
1f7dfb875c Add BogoSort 2019-12-12 14:44:29 -03:00
3 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,41 @@
import Sort from '../Sort';
export default class BogoSort extends Sort {
sort(originalArray) {
// Clone original array to prevent its modification.
let array = [...originalArray];
while (!this.isSorted(array)) { // Verification if is sorted
array = [...this.shuffle(array)]; // Execute shuffle
}
return array;
}
isSorted(array) {
for (let i = 0; i < array.length; i += 1) {
if (array[i - 1] > array[i]) {
return false;
}
}
return true;
}
shuffle(array) {
const newArray = [...array];
let count = array.length;
let index;
let aux;
while (count > 0) {
index = Math.floor(Math.random() * count);
count -= 1;
aux = newArray[count];
newArray[count] = newArray[index];
newArray[index] = aux;
}
return newArray;
}
}

View File

@ -0,0 +1,59 @@
import BogoSort from '../BogoSort';
import {
equalArr,
notSortedArr,
reverseArr,
sortedArr,
SortTester,
} from '../../SortTester';
const SORTED_ARRAY_VISITING_COUNT = 40;
const NOT_SORTED_ARRAY_VISITING_COUNT = 40;
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 40;
const EQUAL_ARRAY_VISITING_COUNT = 40;
describe('BogoSort', () => {
it('should sort array', () => {
SortTester.testSort(BogoSort);
});
it('should sort array with custom comparator', () => {
SortTester.testSortWithCustomComparator(BogoSort);
});
it('should sort negative numbers', () => {
SortTester.testNegativeNumbersSort(BogoSort);
});
it('should visit EQUAL array element specified number of times', () => {
SortTester.testAlgorithmTimeComplexity(
BogoSort,
equalArr,
EQUAL_ARRAY_VISITING_COUNT,
);
});
it('should visit SORTED array element specified number of times', () => {
SortTester.testAlgorithmTimeComplexity(
BogoSort,
sortedArr,
SORTED_ARRAY_VISITING_COUNT,
);
});
it('should visit NOT SORTED array element specified number of times', () => {
SortTester.testAlgorithmTimeComplexity(
BogoSort,
notSortedArr,
NOT_SORTED_ARRAY_VISITING_COUNT,
);
});
it('should visit REVERSE SORTED array element specified number of times', () => {
SortTester.testAlgorithmTimeComplexity(
BogoSort,
reverseArr,
REVERSE_SORTED_ARRAY_VISITING_COUNT,
);
});
});