Last active
February 2, 2021 17:14
-
-
Save fatmali/199c36e4f135a19cc32231db14ff9ea1 to your computer and use it in GitHub Desktop.
Merge Sort in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mergeSort(A: number[]): void { | |
const n = A.length; | |
if (n < 2) { | |
return A; | |
} | |
const mid = Math.floor(n / 2); | |
const left = A.slice(0, mid); | |
const right = A.slice(mid); | |
mergeSort(left); | |
mergeSort(right); | |
merge(left, right, A); | |
} | |
function merge(left: number[], right: number[], A: number[]) { | |
let i = 0; | |
let j = 0; | |
let k = 0; | |
while (i < left.length && j < right.length) { | |
if (left[i] <= right[j]) { | |
A[k] = left[i]; | |
i++; | |
} else { | |
A[k] = right[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i < left.length) { | |
A[k] = left[i]; | |
i++; | |
k++; | |
} | |
while (j < right.length) { | |
A[k] = right[j]; | |
j++; | |
k++; | |
} | |
} | |
const A = [2,9,10,2,1,4,-1,0,-9,3,1] | |
mergeSort(A) | |
console.log(A) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment