Skip to content

Commit 0a4fbaf

Browse files
Javascript_shuffle_issue_fixed
1 parent 5c39e87 commit 0a4fbaf

1 file changed

Lines changed: 16 additions & 9 deletions

File tree

Sorts/BogoSort.js

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,43 @@
33
*/
44
export function isSorted(array) {
55
const length = array.length
6+
67
for (let i = 0; i < length - 1; i++) {
78
if (array[i] > array[i + 1]) {
89
return false
910
}
1011
}
12+
1113
return true
1214
}
1315

1416
/**
15-
* Shuffles the given array randomly in place.
17+
* Shuffles the given array randomly in place
18+
* using the unbiased Fisher–Yates algorithm.
1619
*/
1720
function shuffle(array) {
18-
for (let i = array.length - 1; i; i--) {
19-
const m = Math.floor(Math.random() * i)
20-
const n = array[i - 1]
21-
array[i - 1] = array[m]
22-
array[m] = n
21+
for (let i = array.length - 1; i > 0; i--) {
22+
// Select random index from the inclusive range [0, i]
23+
const j = Math.floor(Math.random() * (i + 1))
24+
25+
// Swap elements
26+
;[array[i], array[j]] = [array[j], array[i]]
2327
}
2428
}
2529

2630
/**
2731
* Implementation of the bogosort algorithm.
2832
*
29-
* This sorting algorithm randomly rearranges the array until it is sorted.
33+
* This sorting algorithm randomly rearranges the array
34+
* until it is sorted.
3035
*
31-
* For more information see: https://en.wikipedia.org/wiki/Bogosort
36+
* For more information see:
37+
* https://en.wikipedia.org/wiki/Bogosort
3238
*/
3339
export function bogoSort(items) {
3440
while (!isSorted(items)) {
3541
shuffle(items)
3642
}
43+
3744
return items
38-
}
45+
}

0 commit comments

Comments
 (0)