Merging sorted arrays together JavaScript


Merging the sorted arrays together in javascript can be done using the sorting techniques available in data structures. In this problem we will be given two sorted arrays and we have to merge them. After merging them, return a single array which is also in a sorted form.

For solving this problem we will use greedy approach.

What are Sorted Arrays ?

In javascript arrays are the collection of similar data types and we can resize the array in run time. Sorted arrays are sequential forms of items of an array. Their order should be in ascending order. In javascript there is a predefined method called sort() is there to sort the elements present in the array. By default the sort() method arranges the elements in ascending order.

// array before sorting
var arr = [2, 5, 1, 3, 6, 9, 7]

//array after sorting
var arr = [1, 2, 3, 5, 6, 7, 9]

Understanding the Problem

To solve this problem we will create a function with two arrays passed as arguments. These arrays are in sorted form already. We have to merge them in a single array.

At the very first step of the function, it will compare the elements of both the sorted arrays and add a smallest element to the newly created array at 0th index. After this step, it will increment the pointer and compare next numbers again and add it at the next index.

We will use a greedy approach in which the top down approach is followed. Greedy approach in data structures is basically followed by selecting the best option available at that particular moment to solve the problem. To understand better let us see an example below:

Algorithm

To merge two given sorted arrays in one sorted array we can use this algorithm. So the step by step procedure as follows:

Step 1: In the first step, define two sorted arrays.

Step 2: Define a function with the name merge2Arrays. And passing two variables in it.

Step 3: Create an empty result array with the given mergedArray to store the merged array in it.

Step 4: In this step we will initialize pointers namely a, b and current to know the position of each element in the array. Here ‘a’ is the index position for the first array, ‘b’ is the index value for the second array and current is the index value for the new merged array.

Step 5: In this step we will initialize a while loop. It will run till the length of both the arrays.

Step 6: Now initialize 2 variables and name them unmerge1 and unmerge2. These variables will store the tracked items of each array defined earlier.

Step 7: Compare the values of both unmerge1 and unmerge2 with index ‘a’ and ‘b’. If unmerge1’s value is less than unmerge2, then add unmerge1 in mergedArray[current]. And increment count for ‘a’ by 1.

Step 8: Now in the else part if unmerge2’s value is less than unmerge1 so add unmerge2 in mergedArray[current] and increment the count for ‘b’ by 1.

Step 9: Outside the if-else block increment the count for ‘current’ by 1.

Step 10: In this step return the mergedArray value.

Step 11: Then call the function defined in step 2 and console the output to see.

Example

// Declaration of two sorted arrays
var array1 = [12, 16, 17, 11, 13];
var array2 = [10, 13, 15, 29, 25];


//define function to merge arrays
function merge2Arrays(array1, array2) {
  let mergedArray = [];
  let a = 0;
  let b = 0;
  let current = 0;

//running a while loop until all elements get sorted
  while (current < ( array1.length + array2.length )) {
     let unmerge1 = array1[a];
     let unmerge2 = array2[b];

     // if next element comes from array1
     if (unmerge1 < unmerge2) {
        mergedArray[current] = unmerge1;
        a++;

     // if next element comes from array2
     } else {
        mergedArray[current] = unmerge2;
        b++;
     }

     current++;
  }

  // return merged array
  return mergedArray;
}

//calling merge2Array function
merge2Arrays(array1, array2);

console.log("Before Merging:")
console.log(array1);
console.log(array2);
console.log("After Merging")
console.log (merge2Arrays(array1, array2));

In the above code firstly we have defined two arrays in sorted order named as array1 and array2. After that we have defined a function called merge2Arrays which takes both defined arrays as arguments. After that mergeArray is initialized as an empty array to store the resultant sorted array.

Then 3 variables a, b and current are initialized to 0, they will work as index values for array1 and array2 and mergedArray.Then we have initialized a while loop to check the smallest element. The loop will run until all elements get sorted. Lastly, return the value of the sorted array.

Output

Before:
[ 12, 16, 17, 11, 13 ]
[ 10, 13, 15, 29, 25 ]
After:
[ 10, 12, 13, 15, 16, 17, 11, 13, 29, 25]

Time complexity

On each iteration of the while loop, the program compares the values of the current elements in the two input arrays with the help of unmerge1 and unmerge2. Then selects the smaller value to add to the mergedArray. It then increments each counter value when required.

The while loop iterates until the sum of array1’s length and array2’s length times. Since each iteration of the loop adds one element to the mergedArray and the array contains a total number of array1 and array2’s elements. The comparisons and pointer increments inside the loop take a constant amount of time, so the overall time complexity of this algorithm is O(N), where N is the sum of n and m. Here n is the length of array1 and m is the length of array2.

Conclusion

With this implementation we have learned how to sort the two sorted arrays with the help of a greedy approach. Greedy approach basically follows top down approach. This technique is called merge sort because it is merging two arrays in one sorted array. And we have learned how to calculate the time complexity of this algorithm which is O(n+k) or O(N).

Updated on: 18-Aug-2023

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements