Skip to content

Instantly share code, notes, and snippets.

@liuwenzhuang
Created February 24, 2021 12:15
Show Gist options
  • Save liuwenzhuang/5f4fd44bd368c87ae578a96548bdd935 to your computer and use it in GitHub Desktop.
Save liuwenzhuang/5f4fd44bd368c87ae578a96548bdd935 to your computer and use it in GitHub Desktop.
merge sorted arrays
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