-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort3.js
76 lines (53 loc) · 1.65 KB
/
mergeSort3.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function merge(array){
if(array.length<=1){
return array
}
let middle=Math.floor(array.length/2)
let left=array.slice(0,middle)
let right=array.slice(middle)
return sort(merge(left),merge(right))
}
function sort(left,right){
let newArray=[]
while (left.length&&right.length) {
if(left[0]<right[0]){
newArray.push(left.shift())
}else{
newArray.push(right.shift())
}
}
return (newArray.concat(left,right))
}
let array=[6,5,4,3,2,1]
let res=merge(array)
console.log(res);
//////////////////////////////////////////////////////////////////////////////
function mergeSort(array) {
if (array.length <= 1) {
return array
}
let midIndex = Math.floor(array.length / 2)
let leftArray = array.slice(0, midIndex)
let rightArray = array.slice(midIndex)
let sortedLeftArray = mergeSort(leftArray)
let sortedRightArray = mergeSort(rightArray)
return merge(sortedLeftArray, sortedRightArray)
}
function merge(leftArray, rightArray) {
const mergedArray = []
let leftIndex = 0
let rightIndex = 0
while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
if (leftArray[leftIndex] < rightArray[rightIndex]) {
mergedArray.push(leftArray[leftIndex])
leftIndex++
} else {
mergedArray.push(rightArray[rightIndex])
rightIndex++
}
}
return mergedArray.concat(leftArray.slice(leftIndex)).concat(rightArray.slice(rightIndex))
}
let unsortedArray = [3, 7, 1, 4, 9, 2, 8, 5, 6]
let sortedArray = mergeSort(unsortedArray)
console.log(sortedArray)