forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.js
52 lines (40 loc) · 1.59 KB
/
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
function mergeSort(unsortedArray, start, end) {
let numberOfPositions = end - start;
if (numberOfPositions > 1) {
let middle = Math.floor((start + end) / 2);
mergeSort(unsortedArray, start, middle);
mergeSort(unsortedArray, middle, end);
mergeTwoSortedArrays(unsortedArray, start, middle, end);
}
return unsortedArray;
}
function mergeTwoSortedArrays(sortedArray, start, middle, end) {
let mergedArray = [];
let mergedArrayPosition = 0;
let firstArrayPosition = start;
let secondArrayPosition = middle;
while (firstArrayPosition < middle && secondArrayPosition < end) {
let firstArrayValue = sortedArray[firstArrayPosition];
let secondArrayValue = sortedArray[secondArrayPosition];
if (firstArrayValue < secondArrayValue) {
mergedArray[mergedArrayPosition] = firstArrayValue;
firstArrayPosition++;
} else {
mergedArray[mergedArrayPosition] = secondArrayValue;
secondArrayPosition++;
}
mergedArrayPosition++;
}
while (firstArrayPosition < middle) {
mergedArray[mergedArrayPosition++] = sortedArray[firstArrayPosition++];
}
while (secondArrayPosition < end) {
mergedArray[mergedArrayPosition++] = sortedArray[secondArrayPosition++];
}
for (let i = 0; i < mergedArrayPosition; i++) {
sortedArray[start + i] = mergedArray[i];
}
}
let unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80];
let sortedArrayViaMergeSort = mergeSort(unsortedArray, 0, unsortedArray.length);
console.log(sortedArrayViaMergeSort);