6 // FIXME: Can't use global resolve or built-in functions by name.
7 // FIXME: Rules about integer truncation.
8 // FIXME: Need to support missing comparator.
9 var bottom_up_merge_sort = (function () {
10 return function bottom_up_merge_sort(comparator)
13 var length = array.length;
16 // Remove holes and undefineds.
17 var undefinedCount = 0;
18 for (var p in array) {
20 if (value === undefined) {
24 copy[copy.length] = value;
31 for (var width = 1; width < n; width = 2 * width) {
32 for (var i = 0; i < n; i = i + 2 * width) {
34 var iRight = Math.min(i + width, n);
35 var iEnd = Math.min(i + 2 * width, n);
40 for (j = iLeft; j < iEnd; j++) {
41 if (i0 < iRight && (i1 >= iEnd || comparator(a[i0], a[i1]) < 0)) {
57 for(var i = 0; i < a.length; i++)
61 // Restore holes and undefineds. Result should be [ values..., undefines..., holes... ].
62 for (var i = 0; i < undefinedCount; ++i)
63 array[array.length] = undefined;
64 array.length = length;
68 function obfuscatedAMinusB(a, b)
75 function aMinusB(a, b)
80 var sortFunctions = [ Array.prototype.sort, bottom_up_merge_sort ];
81 var comparators = [ aMinusB, obfuscatedAMinusB ];
83 function verify(reference, array)
85 for (var i in reference) {
86 if (array[i] !== reference[i]) {
88 log("reference: " + reference);
89 log("array: " + array);
94 if (reference.length != array.length) {
96 log("reference.length: " + reference.length);
97 log("array.length: " + array.length);
101 function benchmark(f, c, array)
103 var start = new Date;
107 // Our time resolution is not very good, so we round down small numbers to
108 // zero in order to show that they are not meaningful.
109 var result = end - start;
113 log(array.length / 1024 + "k:\t" + result + "ms");
116 function makeArrays()
121 for (var count = min; count <= max; count *= 2) {
123 for (var i = 0; i < count; ++i)
124 array[i] = Math.floor(Math.random() * count);
128 arrays.push(new Array(max));
130 arrays.push((function() {
136 // arrays.push((function() {
138 // a[Math.pow(2, 21) - 1] = 1;
146 var arrays = makeArrays();
147 for (var c of comparators) {
148 log("\n" + "===== " + c.name + " =====");
150 for (var f of sortFunctions) {
153 for (var array of arrays) {
154 var copy = array.slice();
155 benchmark(f, c, copy);
156 verify(Array.prototype.sort.call(array.slice(), c), copy);