Skip to content

Commit 781a0e7

Browse files
authored
algorithm: insertion sort (#26)
* feat: add insertionsort algorithm * chore: fix variable declaration
1 parent a42b8db commit 781a0e7

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Sorts/InsertionSort.ts

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @function insertionSort
3+
* @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.
4+
* @param {number[]} num - The input array
5+
* @return {number[]} - The sorted array.
6+
* @see [Insertion Sort](https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c#insertion-sort)
7+
* @example BinaryConvert([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
8+
*/
9+
10+
export const insertionSort = (arr: number[]): number[] => {
11+
for (let i = 1; i < arr.length; i++) {
12+
const temp = arr[i];
13+
let j = i - 1;
14+
while (j >= 0 && arr[j] > temp) {
15+
arr[j + 1] = arr[j];
16+
j--;
17+
}
18+
arr[j + 1] = temp;
19+
}
20+
21+
return arr;
22+
};

Sorts/test/InsertionSort.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { insertionSort } from "../InsertionSort";
2+
3+
describe("Insertion Sort", () => {
4+
it("should return the correct value for average case", () => {
5+
expect(insertionSort([8, 3, 5, 1, 4, 2])).toStrictEqual([1, 2, 3, 4, 5, 8]);
6+
});
7+
8+
it("should return the correct value for worst case", () => {
9+
expect(insertionSort([9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
10+
});
11+
12+
it("should return the correct value for best case", () => {
13+
expect(insertionSort([1, 2, 3, 4, 5, 8])).toStrictEqual([1, 2, 3, 4, 5, 8]);
14+
});
15+
});

0 commit comments

Comments
 (0)