diff --git a/sorts/shell_sort.ts b/sorts/shell_sort.ts new file mode 100644 index 00000000..f9012ee6 --- /dev/null +++ b/sorts/shell_sort.ts @@ -0,0 +1,31 @@ +/** + * @function shellSort + * @description Shell sort algorithm is the optimization for insertion sort algorithm. + * @Complexity_Analysis + * Space complexity - O(1) + * Time complexity + * Best case - Ω(n log(n)) + * Worst case - O(n^2) + * Average case - O(n log(n)^2) + * + * @param {T[]} arr - The input array + * @return {Array} - The sorted array. + * @see [Shell Sort] (https://www.geeksforgeeks.org/shellsort/) + * @example shellSort([4, 1, 8, 10, 3, 2, 5, 0, 7, 6, 9]) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + */ +export function shellSort(arr: T[]): Array { + // start with the biggest gap, reduce gap twice on each step + for (let gap = arr.length >> 1; gap > 0; gap >>= 1) { + for (let i = gap; i < arr.length; i++) { + const temp = arr[i]; + let j = i; // index for compared element on the left side + // shift larger elements down + while (j >= gap && arr[j - gap] > temp) { + arr[j] = arr[j - gap]; + j -= gap; + } + arr[j] = temp; // place i-th element at appropriate position + } + } + return arr; +} diff --git a/sorts/test/shell_sort.test.ts b/sorts/test/shell_sort.test.ts new file mode 100644 index 00000000..695050f4 --- /dev/null +++ b/sorts/test/shell_sort.test.ts @@ -0,0 +1,15 @@ +import { shellSort } from "../shell_sort"; + +describe("Shell Sort", () => { + it("should return the correct value for average case", () => { + expect(shellSort([4, 1, 8, 10, 3, 2, 5, 0, 7, 6, 9])).toStrictEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); + + it("should return the correct value for worst case", () => { + expect(shellSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])).toStrictEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); + + it("should return the correct value for best case", () => { + expect(shellSort([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toStrictEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); +}); \ No newline at end of file