keyを保持したままvalueでソート
javascriptはkeyが勝手に昇順ソートされる。
そういうことはしないで欲しい。
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 |
// (u.js) 'use strict'; module.exports = { p(a) { if(undefined === a){ a = ''; } console.log(a); }, foreach(obj, func) { for (const key of Object.keys(obj)) { const value = obj[key]; func(key, value); } }, dispKeyValue(k, v) { console.log(k + " => " + v); }, getRandomInt(min = 0, max = 9) { min = Number(min); max = Number(max); if (max <= min) { return max; } const randomOffset = Math.floor(Math.random() * (max - min + 1)); return min + randomOffset; } }; |
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 |
// (Main.js) main(); function main() { 'use strict'; const u = require('./u'); const swap = (a, l, r) => { const t = a[l]; a[l] = a[r]; a[r] = t; }; 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 getKeyOfValue = (a, v) => { for (const key of Object.keys(a)) { const value = a[key]; if (v === value) { return key; } } return null; }; const getDeepCopy = (a) => { let b = []; for(const k of Object.keys(a)){ const v = a[k]; b[k] = v; } return b; }; const deepCopy_fromAtoB = (a, b) => { u.foreach(b, (k, v) => { delete b[k]; }); u.foreach(a, (k, v) => { b[k] = v; }); }; const bubblesort_keepkey = (a) => { let b = getDeepCopy(a); bubblesort(b); let c = []; for (const v of b) { const key = getKeyOfValue(a, v); c['_' + key] = v; } // a = getDeepCopy(c); deepCopy_fromAtoB(c, a); }; const sub = () => { const times = 1000000; const a = []; for (let i = 0; i < times; i++) { const n = u.getRandomInt(0, 10); if (undefined === a[n]) { a[n] = 1; } else { a[n] += 1; } } bubblesort_keepkey(a); u.foreach(a, u.dispKeyValue); }; // 実質、main関数 sub(); } |
1 2 3 4 5 6 7 8 9 10 11 |
_8 => 90527 _3 => 90615 _2 => 90618 _9 => 90679 _6 => 90697 _0 => 90701 _5 => 91005 _7 => 91153 _4 => 91288 _1 => 91310 _10 => 91407 |