Skip to content

Commit

Permalink
Added bogo sort
Browse files Browse the repository at this point in the history
  • Loading branch information
mszula committed Jan 7, 2024
1 parent caff6e3 commit 0134f95
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/lib/sort-algorithms/algorithms.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import RangeArraySizePowerOfTwo from "../components/RangeArraySizePowerOfTwo.svelte";
import { bitonicSort } from "./bitonic-sort";
import { bogoSort } from "./bogo-sort";
import { bubleSort } from "./buble-sort";
import { cocktailSort } from "./cocktail-sort";
import { cycleSort } from "./cycle-sort";
Expand Down Expand Up @@ -78,4 +79,8 @@ export const algorithms: AlgorithmDefinition[] = [
name: "Stooge Sort",
function: stoogeSort,
},
{
name: "Bogo Sort",
function: bogoSort,
},
];
34 changes: 34 additions & 0 deletions src/lib/sort-algorithms/bogo-sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { SortingGenerator } from "./types";

function* isSorted(arr: number[]) {
for (var i = 1; i < arr.length; i++) {
yield { access: [i], sound: i };
if (arr[i] < arr[i - 1]) return false;
}
return true;
}

// To generate permutation of the array
function* shuffle(arr: number[]) {
for (let i = 0; i < arr.length; i++) {
const ind = Math.floor(Math.random() * arr.length);
yield { access: [arr.length - i - 1, ind], sound: ind };

const temp = arr[arr.length - i - 1];
arr[arr.length - i - 1] = arr[ind];
arr[ind] = temp;
}
}

// Sorts array a[0..n-1] using Bogo sort
export const bogoSort = function* (a: number[]): SortingGenerator {
const n = a.length;
// if array is not sorted then shuffle
// the array again
let sorted = yield* isSorted(a);
while (!sorted) {
yield* shuffle(a);

sorted = yield* isSorted(a);
}
};

0 comments on commit 0134f95

Please sign in to comment.