Created
February 24, 2021 12:15
-
-
Save liuwenzhuang/5f4fd44bd368c87ae578a96548bdd935 to your computer and use it in GitHub Desktop.
merge sorted arrays
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 mergeArrays(leftArray, rightArray) { | |
const result = []; | |
let leftIndex = 0; | |
let rightIndex = 0; | |
const leftLen = leftArray.length; | |
const rightLen = rightArray.length; | |
while(result.length < leftLen + rightLen) { | |
if (leftIndex < leftLen && (rightIndex === rightLen || leftArray[leftIndex] < rightArray[rightIndex])) { | |
// 左侧数组中含有值 且 (右侧数组中无数据了 或 左侧对应的值小于右侧对应的值) | |
result.push(leftArray[leftIndex]) | |
leftIndex ++; | |
} else { | |
result.push(rightArray[rightIndex]) | |
rightIndex ++; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment