Skip to content

algorithm: insertion sort #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Sorts/InsertionSort.ts
Original file line number Diff line number Diff line change
@@ -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;
};
15 changes: 15 additions & 0 deletions Sorts/test/InsertionSort.test.ts
Original file line number Diff line number Diff line change
@@ -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]);
});
});