-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassicMergeSort.js
77 lines (62 loc) · 2.04 KB
/
classicMergeSort.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
/*
You are given an unsorted list of integers: [38, 27, 43, 3, 9, 82, 10]. Implement the merge sort algorithm to sort this list in ascending order.
Example:
const unsortedArray = [38, 27, 43, 3, 9, 82, 10];
const sortedArray = mergeSort(unsortedArray);
console.log("Sorted Array:", sortedArray);
*/
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
// Split the initial array into halves
const mid = Math.floor(arr.length / 2);
const leftHalf = arr.slice(0, mid);
const rightHalf = arr.slice(mid);
// Recursively sort BOTH halves
const sortedLeft = mergeSort(leftHalf);
const sortedRight = mergeSort(rightHalf);
// Merge the sorted halves
return merge(sortedLeft, sortedRight);
}
function merge(left, right) {
let result = [];
let leftIndex = 0;
let rightIndex = 0;
// Compare elements and merge the subarrays
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
// Add remaining elements from both subarrays
return result.concat(left.slice(leftIndex), right.slice(rightIndex));
}
//EXAMPLE 2: Merge two sorted subarrays into a single sorted array.
function merge(left, right) {
let arr = []
// Break out of loop if any one of the array becomes empty
while (left.length && right.length) {
// Pick the smaller among the smallest element of left and right sub arrays
if (left[0] < right[0]) {
arr.push(left.shift())
} else {
arr.push(right.shift())
}
}
// Concatenating the leftover elements
return [ ...arr, ...left, ...right ]
}
function mergeSort(array) {
const half = array.length / 2
// Base case or terminating case
if(array.length < 2){
return array
}
const left = array.splice(0, half)
return merge(mergeSort(left),mergeSort(array))
}