Merge Two Sorted Arrays into One Sorted Array

Merge two sorted arrays into one sorted array. Given two sorted arrays, write a code to merge them in a sorted manner.

Input:

arr1 = { 1, 5, 6, 7}, arr2 = { 2, 5, 8, 9, 11}

Output:

{1, 2, 5, 5, 6, 7, 8, 9, 11}

Merge Two Sorted Arrays into one sorted array
Merge Two Sorted Arrays

Merge Two Sorted Arrays into One Sorted Array – Java Code

How to merge two sorted arrays? Let’s first discuss their algorithm and then we will write a java code to implement this algorithm.

i) Declare a new array whose size is equal to the sum of the size of array1 plus array2.

ii) Traverse both array simultaneously.

iii) Check if current element of the first array.

  • If it is smaller than the current element of the second array, then store the current element of the first array into the third array and increment the index.
  • If it is larger than the current element of the second array,
    then store the current element of the second array in the third array and increment the index of the second array.

iv) If there are elements left in the first array, append them into the third array.

v) Similarly, If there are elements left in the second array, append them into the third array.

The time complexity of this approach is O(m+n) where m and n is the length of first and second array.

The space complexity is also O(m+n).

Programming video tutorials

Find intersection of two arrays

Find the intersection of two linked lists

Detect loop in a linked list

In this video tutorial, I have explained how we can merge two sorted arrays into a third sorted array.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.