Skip to content

Commit 3787b38

Browse files
21Horzaappgurueu
andauthored
feat: add shell sort (TheAlgorithms#124)
* feat: add shell sort algorithm * feat: add shell sort algorithm * fix: shell sort test * Use shifts instead of floor(x / 2), add some comments --------- Co-authored-by: Lars Müller <[email protected]>
1 parent ee9727f commit 3787b38

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

sorts/shell_sort.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @function shellSort
3+
* @description Shell sort algorithm is the optimization for insertion sort algorithm.
4+
* @Complexity_Analysis
5+
* Space complexity - O(1)
6+
* Time complexity
7+
* Best case - Ω(n log(n))
8+
* Worst case - O(n^2)
9+
* Average case - O(n log(n)^2)
10+
*
11+
* @param {T[]} arr - The input array
12+
* @return {Array<T>} - The sorted array.
13+
* @see [Shell Sort] (https://www.geeksforgeeks.org/shellsort/)
14+
* @example shellSort([4, 1, 8, 10, 3, 2, 5, 0, 7, 6, 9]) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
15+
*/
16+
export function shellSort<T>(arr: T[]): Array<T> {
17+
// start with the biggest gap, reduce gap twice on each step
18+
for (let gap = arr.length >> 1; gap > 0; gap >>= 1) {
19+
for (let i = gap; i < arr.length; i++) {
20+
const temp = arr[i];
21+
let j = i; // index for compared element on the left side
22+
// shift larger elements down
23+
while (j >= gap && arr[j - gap] > temp) {
24+
arr[j] = arr[j - gap];
25+
j -= gap;
26+
}
27+
arr[j] = temp; // place i-th element at appropriate position
28+
}
29+
}
30+
return arr;
31+
}

sorts/test/shell_sort.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { shellSort } from "../shell_sort";
2+
3+
describe("Shell Sort", () => {
4+
it("should return the correct value for average case", () => {
5+
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]);
6+
});
7+
8+
it("should return the correct value for worst case", () => {
9+
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]);
10+
});
11+
12+
it("should return the correct value for best case", () => {
13+
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]);
14+
});
15+
});

0 commit comments

Comments
 (0)