diff --git a/src/lib/sort-algorithms/algorithms.ts b/src/lib/sort-algorithms/algorithms.ts index c47f2d6..52d66c6 100644 --- a/src/lib/sort-algorithms/algorithms.ts +++ b/src/lib/sort-algorithms/algorithms.ts @@ -12,6 +12,7 @@ import { heapSort } from './heap-sort'; import { insertionSort } from './insertion-sort'; import { introSort } from './intro-sort'; import { mergeSort } from './merge-sort'; +import { miracleSort } from './miracle-sort'; import { oddEvenSort } from './odd-even-sort'; import { pancakeSort } from './pancake-sort'; import { quickSort } from './quick-sort'; @@ -96,6 +97,11 @@ export const algorithms: AlgorithmDefinition[][] = [ name: 'Bogo Sort', function: bogoSort, }, + { + name: 'Miracle Sort', + function: miracleSort, + badge: 'new', + }, { name: 'Exchange Sort', function: exchangeSort, diff --git a/src/lib/sort-algorithms/miracle-sort.ts b/src/lib/sort-algorithms/miracle-sort.ts new file mode 100644 index 0000000..209cf2c --- /dev/null +++ b/src/lib/sort-algorithms/miracle-sort.ts @@ -0,0 +1,18 @@ +import type { SortingGenerator } from './types'; + +function* isSorted(arr: number[]) { + for (let i = 1; i < arr.length; i++) { + yield { access: [i], sound: i }; + if (arr[i] < arr[i - 1]) return false; + } + return true; +} + +// Sorts array a[0..n-1] using Miracle sort +export const miracleSort = function* (a: number[]): SortingGenerator { + // if array is not sorted then wait for a miracle to happen + let sorted = yield* isSorted(a); + while (!sorted) { + sorted = yield* isSorted(a); + } +};