From 4f8844bd5a3e78f610581520e3d15c40fcb024cc Mon Sep 17 00:00:00 2001 From: Gustavo Santos Date: Sun, 2 Oct 2022 09:27:06 -0300 Subject: [PATCH 1/2] feat: add insertionsort algorithm --- Sorts/InsertionSort.ts | 22 ++++++++++++++++++++++ Sorts/test/InsertionSort.test.ts | 15 +++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 Sorts/InsertionSort.ts create mode 100644 Sorts/test/InsertionSort.test.ts diff --git a/Sorts/InsertionSort.ts b/Sorts/InsertionSort.ts new file mode 100644 index 00000000..21539692 --- /dev/null +++ b/Sorts/InsertionSort.ts @@ -0,0 +1,22 @@ +/** + * @function insertionSort + * @description simple sortion algorithm for a small number of elements. It compares the `key` element with the previous elements. If the previous elements are greater than the `key` element, then you move the previous element to the next position. + * @param {number[]} num - The input array + * @return {number[]} - The sorted array. + * @see [Insertion Sort](https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c#insertion-sort) + * @example BinaryConvert([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] + */ + +export const insertionSort = (arr: number[]): number[] => { + for (let i = 1; i < arr.length; i++) { + let temp = arr[i]; + let j = i - 1; + while (j >= 0 && arr[j] > temp) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = temp; + } + + return arr; +}; diff --git a/Sorts/test/InsertionSort.test.ts b/Sorts/test/InsertionSort.test.ts new file mode 100644 index 00000000..16aeb38f --- /dev/null +++ b/Sorts/test/InsertionSort.test.ts @@ -0,0 +1,15 @@ +import { insertionSort } from "../InsertionSort"; + +describe("Insertion Sort", () => { + it("should return the correct value for average case", () => { + expect(insertionSort([8, 3, 5, 1, 4, 2])).toStrictEqual([1, 2, 3, 4, 5, 8]); + }); + + it("should return the correct value for worst case", () => { + expect(insertionSort([9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it("should return the correct value for best case", () => { + expect(insertionSort([1, 2, 3, 4, 5, 8])).toStrictEqual([1, 2, 3, 4, 5, 8]); + }); +}); From 48eff388ab8717761b758c46e34f14269041ef0c Mon Sep 17 00:00:00 2001 From: Gustavo Santos Date: Sun, 2 Oct 2022 10:05:11 -0300 Subject: [PATCH 2/2] chore: fix variable declaration --- Sorts/InsertionSort.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorts/InsertionSort.ts b/Sorts/InsertionSort.ts index 21539692..384c09c8 100644 --- a/Sorts/InsertionSort.ts +++ b/Sorts/InsertionSort.ts @@ -9,7 +9,7 @@ export const insertionSort = (arr: number[]): number[] => { for (let i = 1; i < arr.length; i++) { - let temp = arr[i]; + const temp = arr[i]; let j = i - 1; while (j >= 0 && arr[j] > temp) { arr[j + 1] = arr[j];