Skip to content

Commit 5a512df

Browse files
committed
added bogo sort algorithem
1 parent 7988713 commit 5a512df

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

sorts/bogo_sort.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @function bubbleSort
3+
* @description bogo sort is very simple to understand, it randomly shuffeles the input array until it is sorted
4+
* @Complexity_Analysis
5+
* Space complexity - O(1)
6+
* Time complexity
7+
*      Best case   -   O(1)
8+
* The best case occurs when the first shuufle sorts the array.
9+
*      Worst case  -   unbounded
10+
* The worst case occurs when the suffeles never make the array sorted.
11+
*      Average case -  unbounded
12+
* The average case occurs when the suffeles never make the array sorted.
13+
*
14+
* @param {number[]} arr - The input array
15+
* @return {number[]} - The sorted array.
16+
* @see [Bogo Sort](https://en.wikipedia.org/wiki/Bogosort)
17+
* @example bogoSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
18+
*/
19+
export function bogoSort(arr: number[]): number[]{
20+
while(!isSortedArray(arr)){
21+
for (var i = arr.length - 1; i > 0; i--) {
22+
var j = Math.floor(Math.random() * (i + 1));
23+
var temp = arr[i];
24+
arr[i] = arr[j];
25+
arr[j] = temp;
26+
}
27+
}
28+
return arr
29+
}
30+
31+
function isSortedArray(arr: number[]): boolean{
32+
for(let i=0; i < arr.length-1; i++) {
33+
if(arr[i] >= arr[i+1]) {
34+
return false;
35+
}
36+
}
37+
return true;
38+
}

0 commit comments

Comments
 (0)