Created
August 29, 2018 20:05
-
-
Save venil7/da3ff40957484ac9402735a8c4d6f3c2 to your computer and use it in GitHub Desktop.
merge two sorted arrays O(n)
This file contains hidden or 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
| const merge = (a: number[], b: number[]): number[] => { | |
| let length = a.length + b.length; | |
| let result = Array(length); | |
| let i = 0, j = 0, k = 0; | |
| while (i < a.length && j < b.length) { | |
| if (a[i] < b[j]) { | |
| result[k] = a[i]; | |
| i += 1; | |
| } else if (a[i] > b[j]) { | |
| result[k] = b[j] | |
| j += 1 | |
| } else { | |
| result[k] = a[i]; | |
| i += 1; | |
| k += 1; | |
| result[k] = b[j]; | |
| j += 1; | |
| } | |
| k += 1; | |
| } | |
| while (i < a.length) { | |
| result[k] = a[i]; | |
| i += 1; | |
| k += 1; | |
| } | |
| while (j < b.length) { | |
| result[k] = b[j]; | |
| j += 1; | |
| k += 1; | |
| } | |
| return result; | |
| }; | |
| console.log(JSON.stringify(merge( | |
| [0, 1, 2, 3, 5, 14, 19], | |
| [0,4, 7, 8, 9]))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment