diff --git a/src/algorithms/sorting/quick-sort/QuickSortDeclarative.js b/src/algorithms/sorting/quick-sort/QuickSortDeclarative.js new file mode 100644 index 00000000..b145073b --- /dev/null +++ b/src/algorithms/sorting/quick-sort/QuickSortDeclarative.js @@ -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))), + ]; + } +} diff --git a/src/algorithms/sorting/quick-sort/__test__/QuickSortDeclarative.test.js b/src/algorithms/sorting/quick-sort/__test__/QuickSortDeclarative.test.js new file mode 100644 index 00000000..2ecf08bc --- /dev/null +++ b/src/algorithms/sorting/quick-sort/__test__/QuickSortDeclarative.test.js @@ -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, + ); + }); +});