File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33 */
44export 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 */
1720function 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 */
3339export function bogoSort ( items ) {
3440 while ( ! isSorted ( items ) ) {
3541 shuffle ( items )
3642 }
43+
3744 return items
38- }
45+ }
You can’t perform that action at this time.
0 commit comments