两个有序数组合并为一个有序数组

方法一 Array的API实现

const arr_sort = (arr1, arr2) => arr1.concat(arr2).sort((a, b) => a - b)

方法二 遍历其中一个数组 使用二分查找插入另一个数组中

 const arr_sort = function (arr1, arr2) {
    function bsearch (A, x) {
      let l = 0, r = A.length - 1, guess
      while (l <= r) {
        guess = Math.floor((l + r) / 2)
        if (A[guess] === x) {
          return guess
        } else if (A[guess] < x) {
          if (guess === A.length - 1 || A[guess + 1] > x) {
            return guess + 1
          }
          l = guess + 1
        } else {
          if (guess === 0 || A[guess - 1] < x) {
            return guess
          }
          r = guess - 1
        }
      }
    }

    if (arr1.length > arr2.length) {
      arr2.map(item => {
        arr1.splice(bsearch(arr1, item), 0, item)
      })
      return arr1
    } else {
      arr1.map(item => {
        arr2.splice(bsearch(arr2, item), 0, item)
      })
      return arr2
    }
}

你可能感兴趣的:(两个有序数组合并为一个有序数组)