Sorted arrays have sequential arrangements of elements. However, we encounter a problem when we need to merge two sorted arrays into a new sorted array. The idea is to use a merge sorting technique while combining these two sorted arrays.
Click here to learn more about merge sort.
Merge sort is used to merge two sorted arrays. Firstly, the merge function compares the elements of both given sorted arrays and adds a smaller element to the new array. After this, it increments the pointer and compares again. We can see this in the example below:
Here's the code for the implementation of merging two sorted arrays:
#Program to merge two sorted arrays in one arraydef arrayMerger(array1,array2):array3= [] #Array3 will contain merged sorted elements of both array1 and array2i=0 #Counter variablesj=0k=0size1 = len(array1)size2 = len(array2)while i < size1 and j < size2:#Comparing the elements of both arrays and storing in new arrayif array1[i] < array2[j]:array3.append(array1[i])i += 1else:array3.append(array2[j])j += 1#Store remaining elements of first arraywhile i < size1:array3.append(array1[i])i += 1#Store remaining elements of second arraywhile j < size2:array3.append(array2[j])j += 1print 'Array 1:',array1print 'Array 2:' ,array2print 'After Merge'print 'Array 3:',array3# Driver codearray1 = [2,5,8]array2 = [1,3,4]arrayMerger(array1, array2)
The merge function of merge sort is used to implement this code. The steps needed to obtain the sorted merge array through this method can be found below:
Line 3–9: We define the arrayMerger
function in which we create an array3
that has the size of both given arrays. For example, if the size of array1
is 4
, and of array2
is 4
. Then the size of array3
is 4+4 =8
Line 11–19: We use the while
loop to compare the elements of both array1
and array2
traversing simultaneously and adding the smaller element into array3
.
Line 23–31: If some elements are left, copy them into array3
.
With that, two sorted arrays have been merged into one array.
The time complexity of this approach is array1
and array2
.
Free Resources