From 595c01cbb6e34e2305f59c496511b11877cc13c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Szu=C5=82a?= Date: Wed, 3 Jan 2024 00:47:44 +0100 Subject: [PATCH] Added shell sort --- src/lib/sort-algorithms/algorithms.ts | 5 +++++ src/lib/sort-algorithms/shell-sort.ts | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/lib/sort-algorithms/shell-sort.ts diff --git a/src/lib/sort-algorithms/algorithms.ts b/src/lib/sort-algorithms/algorithms.ts index 67c6ecf..51c96e9 100644 --- a/src/lib/sort-algorithms/algorithms.ts +++ b/src/lib/sort-algorithms/algorithms.ts @@ -2,6 +2,7 @@ import { bubleSort } from "./buble-sort"; import { insertionSort } from "./insertion-sort"; import { quickSort } from "./quick-sort"; import { selectionSort } from "./selection-sort"; +import { shellSort } from "./shell-sort"; import type { AlgorithmDefinition } from "./types"; export const algorithms: AlgorithmDefinition[] = [ @@ -21,4 +22,8 @@ export const algorithms: AlgorithmDefinition[] = [ name: "Quick Sort", function: quickSort, }, + { + name: "Shell Sort", + function: shellSort, + }, ]; diff --git a/src/lib/sort-algorithms/shell-sort.ts b/src/lib/sort-algorithms/shell-sort.ts new file mode 100644 index 0000000..c315b0f --- /dev/null +++ b/src/lib/sort-algorithms/shell-sort.ts @@ -0,0 +1,21 @@ +import type { SortingGenerator } from "./types"; + +export const shellSort = function* (arr: number[]): SortingGenerator { + const n = arr.length; + + for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) { + for (var i = gap; i < n; i++) { + let temp = arr[i]; + let j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { + arr[j] = arr[j - gap]; + + yield { accesing: [i, j - gap], sound: j - gap }; + } + + arr[j] = temp; + + yield { accesing: [i, j], sound: j }; + } + } +};