Skip to content

feat: add shell sort #124

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 4 commits into from
Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
31 changes: 31 additions & 0 deletions sorts/shell_sort.ts
Original file line number Diff line number Diff line change
@@ -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<T>} - 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<T>(arr: T[]): Array<T> {
// 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;
}
15 changes: 15 additions & 0 deletions sorts/test/shell_sort.test.ts
Original file line number Diff line number Diff line change
@@ -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]);
});
});