Skip to main content
3 of 3
minus 0.5 and equal comparison without type check

JavaScript, 98 92 chars

More precisely ECMAScript 2015 (ES6)

Minified:

let b=r=>{for(;!r.every((o,t)=>o==[...r].sort()[t]);)r.sort(()=>Math.random()-.5);return r};

Invocation: console.log(b([3, 2, 1, 5, 67, 4, 6, 5, 6, 4]))

Not minified:

let bogoSort = (myArray) => {
  while (!myArray.every((v, i) => v == [...myArray].sort()[i])) {      
    myArray.sort(() => Math.random() -0.5)    
  }
  return myArray
}

Explanation:

  • myArray.every() is an element-wise compare function. Comparing shuffled with sorted array
  • someArray.sort() sorts in place so saving assignments, but also needs cloning for the sorted array
  • [...myArray] clones the array (array destructuring)
  • () => (Math.random() > .5) ? 1 : -1 is a custom compare function. Coin flip whether to order an element in front or behind