-
-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
15 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |