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
| var merge = function(ary, p, q, r) { var l_ary = ary.slice(p, q + 1); var r_ary = ary.slice(q + 1, r + 1); var b_ary;
while (l_ary.length && r_ary.length) { ary[p++] = l_ary[0] <= r_ary[0] ? l_ary.shift() : r_ary.shift(); }
b_ary = l_ary.length ? l_ary : r_ary; while (b_ary.length) { ary[p++] = b_ary.shift(); }
console.log(ary); }
var merge_sort = function(ary, s, e) { var m; if (s === e) return; m = Math.floor((s + e) / 2);
merge_sort(ary, s, m); merge_sort(ary, m + 1, e); merge(ary, s, m, e); }
var do_merge_sort = function() { var ary = [4, 3, 7, 1, 9, 2, 6, 5];
console.log(ary); merge_sort(ary, 0, ary.length - 1);
console.log(ary); }
do_merge_sort();
|