-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.js
More file actions
59 lines (43 loc) · 1.21 KB
/
Copy pathmergeSort.js
File metadata and controls
59 lines (43 loc) · 1.21 KB
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
let sortedarr = []
const merge = (dupbars, low, mid, high) => {
let i = low, j = mid + 1
const arr = []
while((i <= mid) && (j <= high)){
sortedarr.push([i, j, null, null])
if(dupbars[i] <= dupbars[j]){
arr.push(dupbars[i++])
} else {
arr.push(dupbars[j++])
}
}
while(i <= mid){
sortedarr.push([i, null, null, null])
arr.push(dupbars[i++])
}
while(j <= high){
sortedarr.push([null, j, null, null])
arr.push(dupbars[j++])
}
for(i=low;i<=high;i++){
dupbars[i] = arr[i - low]
sortedarr.push([i, null, dupbars.slice(), null])
}
}
const mergeSortHelper = (dupbars, low, high) => {
if(low >= high)
return
const mid = Math.floor((low + high) / 2)
mergeSortHelper(dupbars, low, mid)
mergeSortHelper(dupbars, mid + 1, high)
merge(dupbars, low, mid, high)
}
const mergeSort = (bars) => {
sortedarr = []
const dupbars = bars.slice()
mergeSortHelper(dupbars, 0, dupbars.length - 1)
for(let i=0;i<dupbars.length;i++){
sortedarr.push([null, null, null, i])
}
return sortedarr
}
export default mergeSort