From 1dc5cd8f59bbc68dc59801b08412e343344b0387 Mon Sep 17 00:00:00 2001 From: Adhiraj Date: Sat, 8 Oct 2022 03:49:23 +0530 Subject: [PATCH 1/2] Create QuickSort.ts --- Sorts/QuickSort.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Sorts/QuickSort.ts diff --git a/Sorts/QuickSort.ts b/Sorts/QuickSort.ts new file mode 100644 index 00000000..5ece603d --- /dev/null +++ b/Sorts/QuickSort.ts @@ -0,0 +1,30 @@ +/** + * @function QuickSort + * @description a comparison sorting algorithm that uses a divide and conquer strategy + * @param {number[]} arr - array of integers + * @return {number[]} arr - sorted array + * @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort) + * @example QuickSort([5, 4, 3, 2, 1]) = [1, 2, 3, 4, 5] + * @example QuickSort([9, -4, 3, 6, 1]) = [-4, 1, 3, 6, 9] + */ +export const QuickSort = (arr: number[]): number[] => { + const len = arr.length; + + if (len <= 1) { + return arr; + } + const PIVOT = arr[0]; + const GREATER : number[] = []; + const LESSER : number[] = []; + + for (let i = 1; i < len; i++) { + if (arr[i] > PIVOT) { + GREATER.push(arr[i]); + } else { + LESSER.push(arr[i]); + } + } + + const sorted = [...QuickSort(LESSER), PIVOT, ...QuickSort(GREATER)]; + return sorted; +} From 3084919ec6af3b328ff4fc257bf802d82125a00c Mon Sep 17 00:00:00 2001 From: Adhiraj Date: Sat, 8 Oct 2022 03:50:07 +0530 Subject: [PATCH 2/2] Create QuickSort.test.ts --- Sorts/test/QuickSort.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Sorts/test/QuickSort.test.ts diff --git a/Sorts/test/QuickSort.test.ts b/Sorts/test/QuickSort.test.ts new file mode 100644 index 00000000..f109bf57 --- /dev/null +++ b/Sorts/test/QuickSort.test.ts @@ -0,0 +1,10 @@ +import { QuickSort } from "../QuickSort"; + +describe("Quick Sort", () => { + it("should sort all arrays correctly", () => { + expect(QuickSort([4, 1, 3, 5, 6, 7, 2])).toStrictEqual([1, 2, 3, 4, 5, 6, 7]); + expect(QuickSort([8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(QuickSort([8, 4, 10, 15, 9])).toStrictEqual([4, 8, 9, 10, 15]); + expect(QuickSort([1, 2, 3])).toStrictEqual([1, 2, 3]); + }); +});