forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.js
52 lines (47 loc) · 1.15 KB
/
Main.js
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
var buf = '';
process.stdin.on('readable', function () {
var chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputArgs = line => {
return line
.split(' ')
.filter(s => s !== '')
.map(x => parseInt(x));
};
function mergeSort(nums, left, right) {
if (left >= right) {
return;
}
const mid = (left + right) >> 1;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
let i = left;
let j = mid + 1;
let tmp = [];
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
tmp.push(nums[i++]);
} else {
tmp.push(nums[j++]);
}
}
while (i <= mid) {
tmp.push(nums[i++]);
}
while (j <= right) {
tmp.push(nums[j++]);
}
for (i = left, j = 0; i <= right; ++i, ++j) {
nums[i] = tmp[j];
}
}
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx % 2 === 1) {
nums = getInputArgs(line);
mergeSort(nums, 0, nums.length - 1);
console.log(nums.join(' '));
}
});
});