how to merge 2 sorted arrays code example
Example 1: Write a function that takes in two sorted arrays and returns a new array with all elements sorted not using array method sort.
// const newSortArrays = (arr1, arr2) => {
// let output = [];
// while (arr1.length && arr2.length) {
// if (arr1[0] < arr2[0])
// output.push(arr1[0] < arr2[0] ? arr1.shift() : arr2.shift())
// }
// return [...output, ...arr1, ...arr2]
// }
Example 2: write a function that takes in 2 arrays , merges them together an then return the new array sorted
// const twoArraysSorted = (arr) => {
// let copy = [...];
// copy.sort((a,b) => a-b).map(el=> el*2)
// return arr
// }
Example 3: In-place merge two sorted arrays
def merge(X, Y):
m = len(X)
n = len(Y)
for i in range(m):
if X[i] > Y[0]:
temp = X[i]
X[i] = Y[0]
Y[0] = temp
first = Y[0]
k = 1
while k < n and Y[k] < first:
Y[k - 1] = Y[k]
k = k + 1
Y[k - 1] = first