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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
function merge(arr, left, mid, right) {
const THRESHOLD = 7; if (right - left <= THRESHOLD) { insertionSort(arr, left, right); return; }
let n1 = mid - left + 1; let n2 = right - mid;
let leftArr = []; let rightArr = [];
for (let i = 0; i < n1; i++) { const element = arr[i + left]; leftArr.push(element) } for (let i = 0; i < n2; i++) { const element = arr[i + mid + 1]; rightArr.push(element) }
let i = 0, j = 0, k = left;
while (i < n1 && j < n2) { if (leftArr[i] < rightArr[j]) { arr[k] = leftArr[i]; i++ } else { arr[k] = rightArr[j]; j++ }
k++; }
while (i < n1) { arr[k] = leftArr[i]; i++; k++; } while (j < n2) { arr[k] = rightArr[j]; j++; k++; } }
function insertionSort(arr, left, right) { for (let i = left + 1; i <= right; i++) { let currVal = arr[i]; let j = i - 1;
while (j >= 0 && arr[j] > currVal) { arr[j + 1] = arr[j]; j--; }
arr[j + 1] = currVal; } }
function mergeSort(arr, left, right) { if (left < right) { let mid = parseInt((right + left) / 2) mergeSort(arr, left, mid) mergeSort(arr, mid + 1, right) merge(arr, left, mid, right); } }
let arr = [12, 6, 13, 5, 14, 7, 122, 323, 1234, 54, 56, 54, 32, 1223, 3445, 1234]; mergeSort(arr, 0, arr.length - 1) console.log(arr)
|