1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function partition(ary, comparator, start = 0, end = ary.length - 1, ) { if (start >= end) { return }
var pivotIndex = Math.floor(Math.random() * (end - start + 1) + start) var pivot = ary[pivotIndex]
swap(ary, pivotIndex, end)
for(var i = start - 1, j = start; j < end; j++) { if (comparator(ary[j], pivot) < 0) { i++ swap(ary, i, j) } }
swap(ary, i + 1, end) partition(ary, comparator, start, i) partition(ary, comparator, i + 2, end) return ary }
function quickSort(ary, comparator = (a,b) => a - b) { return partition(ary, comparator) }
|