Skip to content

Commit

Permalink
Added shell sort
Browse files Browse the repository at this point in the history
  • Loading branch information
mszula committed Jan 2, 2024
1 parent a8391df commit 595c01c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/lib/sort-algorithms/algorithms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [
Expand All @@ -21,4 +22,8 @@ export const algorithms: AlgorithmDefinition[] = [
name: "Quick Sort",
function: quickSort,
},
{
name: "Shell Sort",
function: shellSort,
},
];
21 changes: 21 additions & 0 deletions src/lib/sort-algorithms/shell-sort.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
}
};

0 comments on commit 595c01c

Please sign in to comment.