merge two 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: In-place merge two sorted arrays

def merge(X, Y):
 
    m = len(X)
    n = len(Y)
 
    # Consider each element `X[i]` of list `X[]` and ignore the element if it is
    # already in the correct order; otherwise, swap it with the next smaller
    # element, which happens to be the first element of `Y[]`.
    for i in range(m):
 
        # compare the current element of `X[]` with the first element of `Y[]`
        if X[i] > Y[0]:
 
            # swap `X[i] with `Y[0]`
            temp = X[i]
            X[i] = Y[0]
            Y[0] = temp
 
            first = Y[0]
 
            # move `Y[0]` to its correct position to maintain the sorted
            # order of `Y[]`. Note: `Y[1…n-1]` is already sorted
            k = 1
            while k < n and Y[k] < first:
                Y[k - 1] = Y[k]
                k = k + 1
 
            Y[k - 1] = first

Example 3: merge two sorted lists python

from heapq import merge 
  
# initializing lists 
test_list1 = [1, 5, 6, 9, 11] 
test_list2 = [3, 4, 7, 8, 10] 
  
# printing original lists  
print ("The original list 1 is : " + str(test_list1)) 
print ("The original list 2 is : " + str(test_list2)) 
  
# using heapq.merge() 
# to combine two sorted lists 
res = list(merge(test_list1, test_list2)) 
  
# printing result 
print ("The combined sorted list is : " + str(res))

Example 4: merge two sorted list in python

# l1 and l2 are lists
sorted(l1+l2)

Tags:

Java Example