Skip to content

Commit

Permalink
Stooge sort better visualization
Browse files Browse the repository at this point in the history
  • Loading branch information
mszula committed Jun 27, 2024
1 parent 612fd8b commit adc3d8e
Showing 1 changed file with 15 additions and 22 deletions.
37 changes: 15 additions & 22 deletions src/lib/sort-algorithms/stooge-sort.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
import type { SortingGenerator } from './types';

function* stoogeSortRun(arr: number[], l: number, h: number): SortingGenerator {
if (l >= h) return;

yield { access: [l, h], sound: l };
function* sort(arr: number[], l: number, h: number): SortingGenerator {
if (l >= h) {
return;
}

// If first element is smaller
// than last, swap them
// If first element is smaller than last, swap them
if (arr[l] > arr[h]) {
const t = arr[l];
arr[l] = arr[h];
arr[h] = t;
[arr[l], arr[h]] = [arr[h], arr[l]];
yield { access: [l, h], sound: l };
}

// If there are more than 2
// elements in the array
// If there are more than two elements in the array
if (h - l + 1 > 2) {
const t = Math.floor((h - l + 1) / 3);

// Recursively sort first
// 2/3 elements
yield* stoogeSortRun(arr, l, h - t);
// Recursively sort first 2/3 elements
yield* sort(arr, l, h - t);

// Recursively sort last
// 2/3 elements
yield* stoogeSortRun(arr, l + t, h);
// Recursively sort last 2/3 elements
yield* sort(arr, l + t, h);

// Recursively sort first
// 2/3 elements again to
// confirm
yield* stoogeSortRun(arr, l, h - t);
// Recursively sort first 2/3 elements again to confirm
yield* sort(arr, l, h - t);
}
}

export const stoogeSort = function* (arr: number[]): SortingGenerator {
yield* stoogeSortRun(arr, 0, arr.length - 1);
yield* sort(arr, 0, arr.length - 1);
};

0 comments on commit adc3d8e

Please sign in to comment.