From db0ac91d81c6b0a1b30595efd63bb27e07fac1fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Szu=C5=82a?= Date: Wed, 3 Jan 2024 00:00:35 +0100 Subject: [PATCH] Added selection sort --- README.md | 2 +- src/lib/sort-algorithms/algorithms.ts | 5 +++++ src/lib/sort-algorithms/selection-sort.ts | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/lib/sort-algorithms/selection-sort.ts diff --git a/README.md b/README.md index 887a73e..fd7d0a8 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ https://github.com/mszula/visual-sorting/assets/17621834/3077ad21-ed6e-432c-ae51 ## 🤖 Supported Sorting Algorithms - Bubble Sort -- Selection Sort (soon) +- Selection Sort - Insertion Sort - Quick Sort diff --git a/src/lib/sort-algorithms/algorithms.ts b/src/lib/sort-algorithms/algorithms.ts index ff0abe0..67c6ecf 100644 --- a/src/lib/sort-algorithms/algorithms.ts +++ b/src/lib/sort-algorithms/algorithms.ts @@ -1,6 +1,7 @@ import { bubleSort } from "./buble-sort"; import { insertionSort } from "./insertion-sort"; import { quickSort } from "./quick-sort"; +import { selectionSort } from "./selection-sort"; import type { AlgorithmDefinition } from "./types"; export const algorithms: AlgorithmDefinition[] = [ @@ -12,6 +13,10 @@ export const algorithms: AlgorithmDefinition[] = [ name: "Insertion Sort", function: insertionSort, }, + { + name: "Selection Sort", + function: selectionSort, + }, { name: "Quick Sort", function: quickSort, diff --git a/src/lib/sort-algorithms/selection-sort.ts b/src/lib/sort-algorithms/selection-sort.ts new file mode 100644 index 0000000..57a19bd --- /dev/null +++ b/src/lib/sort-algorithms/selection-sort.ts @@ -0,0 +1,21 @@ +import type { SortingGenerator } from "./types"; + +export const selectionSort = function* (arr: number[]): SortingGenerator { + const n = arr.length; + + for (let i = 0; i < n; i++) { + let min = i; + for (let j = i + 1; j < n; j++) { + if (arr[j] < arr[min]) { + min = j; + } + yield { accesing: [i, j], sound: j }; + } + if (min != i) { + let tmp = arr[i]; + arr[i] = arr[min]; + arr[min] = tmp; + } + yield { accesing: [i], sound: i }; + } +};