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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
'use strict' const main = () => { const p = console.log const getRandomInt = (min = 0, max = 9) => { const offset = Math.floor(Math.random() * (max - min + 1)) return min + offset } const getBlankArray = (size = 10) => { const a = [] for (let i = 0; i < size; i++) { a[i] = 0 } return a } const dispArrayList = a => { const len = a.length for (let i = 0; i < len; i++) { p(i + " => " + a[i]) } } const setRandomForArray = (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 ? b : c } } } const swap = (a, left, right) => { const t = a[left] a[left] = a[right] a[right] = 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 bubblesort = a => { const len = a.length for (let i = 0; i < len - 1; i++) { for (let j = i + 1; j < len; j++) { if (a[j] < a[i]) { swap(a, i, j) } } } } const getCloneArray = a => { const len = a.length const b = [] for (let i = 0; i < len; i++) { b[i] = a[i] } return b } const sub = () => { const a = getBlankArray(20) setRandomForArray(a) const b = getCloneArray(a) p("a : " + a) p("b : " + b) quicksort(a) bubblesort(b) p("a : " + a) p("b : " + b) } sub() } main() |
1 2 3 4 |
a : 3,1,7,4,6,2,4,2,3,9,7,1,8,0,4,7,4,2,3,8 b : 3,1,7,4,6,2,4,2,3,9,7,1,8,0,4,7,4,2,3,8 a : 0,1,1,2,2,2,3,3,3,4,4,4,4,6,7,7,7,8,8,9 b : 0,1,1,2,2,2,3,3,3,4,4,4,4,6,7,7,7,8,8,9 |