-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbogo.ts
40 lines (36 loc) · 1.15 KB
/
bogo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { compare } from '../../utils/compare'
import { swap } from '../../utils/swap'
/**
* Bogo Sort is highly inefficient algorithm and sometimes referred as
* "stupid sort" based on generate and test paradigm. Function shuffle repeadetly
* generates random permutation of it's input until it finds one that is sorted.
* Bogo Sort is not suitable for real-world applications.
*
* Time Complexity:
* Average Case: O ((n +1)!)
* Worst Case: Is unbounded since there is no guarantee it will complete
*
* @param arr unsorted array
* @returns sorted array
*/
export function bogoSort<TElement extends string | number>(arr: TElement[]): TElement[] {
while (isNotSorted(arr)) {
shuffle(arr)
}
return arr
}
function shuffle<TElement extends string | number>(arr: TElement[]): void {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
swap(arr, i, j)
}
}
function isNotSorted<TElement extends string | number>(arr: TElement[]): boolean {
for (let i = 1; i < arr.length; i++) {
if (compare(arr[i - 1], arr[i]) > 0) {
return true
}
}
return false
}
export type BogoSortFn = typeof bogoSort