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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
'use strict'; const getPivot = (a, b, c) => { if (b < a) { if (a < c) { return a; } else { return b < c ? c : b; } } else { if (b < c) { return b; } else { return a < c ? c : a; } } }; const swap = (a, l, r) => { const t = a[l]; a[l] = a[r]; a[r] = t; }; const quicksort = (a, left = 0, right = null) => { if (null === right) { right = a.length - 1; } if (right <= left) { return; } let l = left; let r = right; const p = getPivot(a[l], a[l + 1], a[r]); while (true) { while (a[l] < p) { l++; } while (p < a[r]) { r--; } if (r <= l) { break; } swap(a, l, r); l++; r--; } quicksort(a, left, l - 1); quicksort(a, r + 1, right); }; const main = () => { const a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; quicksort(a); console.log(a); }; main(); |
1 2 3 4 |
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |