How to merge two sorted arrays?

Data Structure >   Array >   Array Introduction in Data Structure  

Short Question

613


Answer:

Assume, that both arrays are sorted in ascending order and we want resulting array to maintain the same order. Algorithm to merge two arrays A[0..m-1] and B[0..n-1] into an array C[0..m+n-1] is as following:
1. Introduce read-indices i, j to traverse arrays A and B, accordingly. Introduce write-index k to store position of the first free cell in the resulting array. By default i = j = k = 0.
2. At each step: if both indices are in range (i < m and j < n), choose minimum of (A[i], B[j]) and write it to C[k]. Otherwise go to step 4.
3. Increase k and index of the array, algorithm located minimal value at, by one. Repeat step 2.
4. Copy the rest values from the array, which index is still in range, to the resulting array.


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.