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 55 56 57 58 59 |
'use strict'; const p = console.log; const swap = (a, l, r) => { const t = a[l]; a[l] = a[r]; a[r] = t; }; const getPivot = (a, b, c) => { if (a > b) { if (b > c) { return b; } else { return a > c ? c : a; } } else { if (a > c) { return a; } else { return b > c ? b : c; } } }; const quicksort = (a, left = 0, right = null) => { if (null === right) { right = a.length - 1; } if (left >= right) { return; } let l = left; let r = right; const pivot = getPivot(a[l], a[l + 1], a[r]); while (true) { if (a[l] < pivot) { l++; } if (pivot < a[r]) { r--; } if (l >= r) { break; } swap(a, l, r); l++; r--; } quicksort(a, left, l - 1); quicksort(a, r + 1, right); }; const a = [4, 3, 2, 1, 0]; p(a); quicksort(a); p(a); |
1 2 |
[ 4, 3, 2, 1, 0 ] [ 0, 1, 2, 3, 4 ] |