-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
114 lines (83 loc) · 2.48 KB
/
index.html
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
109
110
111
112
113
114
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment</title>
</head>
<body>
<script type="text/javascript">
var debug = 1;
function out(st) {
document.write('<p>'+ st + '</p>');
try {
if (debug)
console.log(st);
} catch(e) {}
}
function generateRandomArray(n) {
var arr = [];
for (var i=0; i < n; i ++) {
arr.push(Math.floor( Math.random() * n + n));
}
return arr.sort();
}
/**
* Merge all elements in a and b, sorted in descending order.
*
* @param {Array}, {Array} source arrays to merge and sort
* @return {Array} resulting merged array
*/
function mergeAndReorder(a, b) {
var result = [];
while ((a.length != 0) && (b.length != 0)) {
if (a[a.length - 1] >= b[b.length - 1]) {
result.push(a.pop());
} else {
result.push(b.pop());
}
}
while (a.length != 0) {
result.push( a.pop());
}
while (b.length != 0) {
result.push( b.pop());
}
return result;
}
/**
* Run a test to join the arrays using build in methods and the assignment method.
* Display output (if not too large) and execution times, finally are the results
* as expected.
*
* @param {String}, {Array}, {Array} Title and the two source arrays
*/
function test(title, a, b) {
out(title);
if (a.length < 50)
out('a: '+ a);
if (b.length < 50)
out('b: '+ b);
var t0 = performance.now();
var z = a.concat(b).sort(function(a, b){return b-a});
if (z.length < 50)
out(z);
var t1 = performance.now();
out('concat-sort: '+ (t1 - t0).toFixed(4) +'ms');
t0 = performance.now();
var result = mergeAndReorder(a, b)
if (result.length < 50)
out(result);
t1 = performance.now();
out('assignment:'+ (t1 - t0).toFixed(4) +'ms');
out('Equals: '+ (JSON.stringify(z) === JSON.stringify(result)) );
}
var a = [1, 3, 5, 7, 9]
,b = [2, 4, 6, 8, 10];
var n = 50
,c = generateRandomArray(n)
,d = generateRandomArray(n)
test('Simple', a, b);
test('Long ('+ n +')', c, d);
</script>
</body>
</html>