Skip to content

Commit

Permalink
Added selection sort
Browse files Browse the repository at this point in the history
  • Loading branch information
mszula committed Jan 2, 2024
1 parent b212104 commit db0ac91
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions src/lib/sort-algorithms/algorithms.ts
Original file line number Diff line number Diff line change
@@ -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[] = [
Expand All @@ -12,6 +13,10 @@ export const algorithms: AlgorithmDefinition[] = [
name: "Insertion Sort",
function: insertionSort,
},
{
name: "Selection Sort",
function: selectionSort,
},
{
name: "Quick Sort",
function: quickSort,
Expand Down
21 changes: 21 additions & 0 deletions src/lib/sort-algorithms/selection-sort.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
};

0 comments on commit db0ac91

Please sign in to comment.