Example:
Input Array 1: {1, 2, 3} Input Array 2: {4, 5, 6} Output Array: {1, 2, 3, 4, 5, 6}
merge sort
to create the resultant array.
1. Declare and initialize 3
counters to 0
to keep track of the positions of input Array 1, 2
and the output array
.
2. Start a loop
to traverse through the elements of input Array 1 and 2
. Make sure it runs till either of position counters
are less than the size
of the respective arrays.
3. Compare the elements at the current positions in input Array 1
and Array 2
. Insert the smaller element to the output array
and increment the position counters
of respective arrays by 1
.
4. At the end of the loop
, insert all the left over elements from the input arrays to the output
array as is.
5. Return the output
array. This has all the elements from both the input arrays in a sorted
manner.
public static int[] mergeSortedArrays(int[] inputSortedArray1, int [] inputSortedArray2) { }
C
Java
Python