-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSORT - MergeSort.js
88 lines (44 loc) · 1.54 KB
/
SORT - MergeSort.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
77
78
79
80
81
82
83
84
85
86
87
88
// ====================================MERGE SORT====================================
function mergeSort(arr, lowIndex = 0, highIndex = arr.length - 1) {
if (lowIndex >= highIndex){ // Base Condition for Recursion
return;
}
const mid = Math.floor((lowIndex + highIndex) / 2);
mergeSort(arr, lowIndex, mid); // left half
mergeSort(arr, mid + 1, highIndex); // right half
merge(arr, lowIndex, mid, highIndex); // merging sorted halves
}
function merge(arr, lowIndex, mid, highIndex) {
const temp = []; // temporary array
let left = lowIndex; // starting index of left half of arr
let right = mid + 1; // starting index of right half of arr
//storing elements in the temporary array in a sorted manner//
while (left <= mid && right <= highIndex) {
if (arr[left] <= arr[right]) {
temp.push(arr[left]);
left++;
} else {
temp.push(arr[right]);
right++;
}
}
// If there are elements remaining on the Left half //
while (left <= mid) {
temp.push(arr[left]);
left++;
}
// If there are elements remaining on the Right half //
while (right <= highIndex) {
temp.push(arr[right]);
right++;
}
// Transferring all elements from temporary to arr //
for (let i = lowIndex; i <= highIndex; i++) {
arr[i] = temp[i - lowIndex];
}
}
// =============================TEST CASE=============================
const arr1 = [9, 4, 7, 6, 3, 1, 5];
console.log("Before sorting array: " + arr1);
mergeSort(arr1);
console.log("After sorting array: " + arr1);