JSFiddle - React, Tailwind, and code Playground

by Ilya Karpuk

JavaScript

function bogoSort(array){
     var startTime = new Date().getTime()
 
     function isSorted(array){
         for (var i = 0; i < array.length - 1; i++){
             if (array[i] > array[i+1]) return false
         }
         return true
     }
    
    function randomSort(){  
        // Javascript's array sort() function can take a function to sort the array
        // The function is supposed to return a negative, zero, or positive value depending
        // on which of the input values is larger
        return 0.5 - Math.random()
    }
       
    while (!isSorted(array)){
        array = array.sort(randomSort)
    }

    // Get total time
    var time = new Date().getTime() - startTime
    console.log('Total time: ' + time/1000.0 + ' seconds') // This part won't work if you don't have firebug installed
    
    return array
    
}