-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge-sort.js
53 lines (50 loc) · 1.04 KB
/
merge-sort.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
53
function sort(array, m){
let mass = [];
for(let i = 0; i < m; i ++){
mass.push(array[i]);
}
if(m <= 1){
array[0] = mass[0];
}
else{
let l = [];
let r = [];
for(let i = 0; i < m; i ++){
if(i < Math.floor(m / 2)){
l.push(mass[i]);
}
else{
r.push(mass[i]);
}
}
sort(l, l.length);
sort(r, r.length);
let h = 0;
let f = 0;
let c = [];
while(h < l.length && f < r.length){
if(l[h] < r[f]){
c.push(l[h]);
h += 1;
}
else{
c.push(r[f]);
f += 1;
}
}
while(h < l.length){
c.push(l[h]);
h += 1;
}
while(f < r.length){
c.push(r[f]);
f += 1;
}
for(let i = 0; i < m; i++){
array[i] = c[i];
}
}
}
let a = [];
sort(a, a.length);
console.log(a);