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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
const main = () => { const p = console.log const getRandomInt = (min = 0, max = 9) => { const randomOffset = Math.floor(Math.random() * (max - min + 1)) return min + randomOffset } const dispArrayList = a => { a.forEach((v, k) => { p(k + " => " + v) }) } const getBlankArray = (len = 10) => { const a = [] for (let i = 0; i < len; i++) { a[i] = 0 } return a } const setRandomIntForArray = (a, min = 0, max = 9) => { const len = a.length for (let i = 0; i < len; i++) { a[i] = getRandomInt(min, max) } } 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 ? c : b } } } const swap = (a, l, r) => { const t = a[l] a[l] = a[r] a[r] = t } const quicksort = (a, left = 0, right = -1) => { if (right === -1) { 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 sub = () => { const a = getBlankArray(30) setRandomIntForArray(a) p("ソート前", a) quicksort(a) p("ソート後", a) } sub() } main() |
1 2 |
ソート前 [ 8, 2, 7, 5, 4, 8, 0, 1, 6, 7, 7, 3, 8, 0, 7, 9, 5, 0, 4, 4, 1, 1, 3, 5, 1, 8, 9, 1, 0, 8 ] ソート後 [ 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9 ] |