Add declarative version of quick sort

This commit is contained in:
Kamil Breguła 2019-06-16 17:50:23 +02:00
parent 94abfec91d
commit 7bdd956478
2 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,23 @@
import Sort from '../Sort';
export default class QuickDeclarativeSort extends Sort {
/**
* @param {*[]} originalArray
* @return {*[]}
*/
sort(originalArray) {
if (originalArray.length < 1) {
return originalArray;
}
const array = [...originalArray];
const currentElement = array.shift();
this.callbacks.visitingCallback(currentElement);
return [
...this.sort(array.filter(element => this.comparator.lessThan(element, currentElement))),
currentElement,
...this.sort(array.filter(element => !this.comparator.lessThan(element, currentElement))),
];
}
}

View File

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