diff --git a/src/sort/quick/quickSort.spec.ts b/src/sort/quick/quickSort.spec.ts new file mode 100644 index 0000000..c7c2fce --- /dev/null +++ b/src/sort/quick/quickSort.spec.ts @@ -0,0 +1,41 @@ +import quickSort from './quickSort'; + +const sortLowToHigh = (a: number, b: number): boolean => (a < b); +const sortHighToLow = (a: number, b: number): boolean => (a > b); + +describe('quick sort', () => { + it('should return an empty array when the array for sorting is empty', () => { + const arrayToSort: number[] = []; + const expectedArray: number[] = []; + expect(quickSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array with the element', () => { + const arrayToSort: number[] = [14]; + const expectedArray: number[] = [14]; + expect(quickSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array with two elements sorted from lowest to highest', () => { + const arrayToSort = [65, 43]; + const expectedArray = [43, 65]; + expect(quickSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array sorted from lowest to highest', () => { + const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21]; + const expectedArray = [1, 9, 12, 21, 33, 43, 44, 65, 67]; + expect(quickSort(arrayToSort, sortLowToHigh)) + .toEqual(expectedArray); + }); + + it('should return an array sorted from highest to lowest', () => { + const arrayToSort = [43, 65, 44, 12, 67, 1, 9, 33, 21]; + const expectedArray = [67, 65, 44, 43, 33, 21, 12, 9, 1]; + expect(quickSort(arrayToSort, sortHighToLow)) + .toEqual(expectedArray); + }); +}); diff --git a/src/sort/quick/quickSort.ts b/src/sort/quick/quickSort.ts new file mode 100644 index 0000000..fe0fd36 --- /dev/null +++ b/src/sort/quick/quickSort.ts @@ -0,0 +1,29 @@ +interface CompareFunction { + (a: number, b: number): boolean; +} + +export default function quickSort(array: number[], compareFunction: CompareFunction): number[] { + if (array.length < 2) { + return array; + } + const pivot = array[Math.floor(Math.random() * array.length)]; + + const left: number[] = []; + const right: number[] = []; + const equal: number[] = []; + + array.forEach((value) => { + if (compareFunction(value, pivot)) { + left.push(value); + } else if (!compareFunction(value, pivot)) { + right.push(value); + } else { + equal.push(value); + } + }); + return [ + ...quickSort(left, compareFunction), + ...equal, + ...quickSort(right, compareFunction), + ]; +}