Merging two sorted arrays into a single sorted array is a common task in many algorithms, including Merge Sort. When two arrays are already sorted, merging them can be done in linear time. This technique is useful in various applications like sorting, searching, and combining datasets efficiently.
Given two sorted arrays, the task is to merge them into a single sorted array. The input arrays are sorted in non-decreasing order, and the merged array should also be sorted in non-decreasing order.
Let’s say we have two sorted arrays:
After merging these arrays, the output will be:
Initialize Pointers:
Compare Elements:
Handle Remaining Elements:
Here’s the step-by-step approach to merge two sorted arrays:
python
Copy code
def merge_arrays(arr1, arr2): # Resultant array to store the merged elements merged_array = [] # Pointers for arr1 and arr2 i, j = 0, 0 # Traverse both arrays and compare elements while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: merged_array.append(arr1[i]) i += 1 else: merged_array.append(arr2[j]) j += 1 # Add the remaining elements of arr1, if any while i < len(arr1): merged_array.append(arr1[i]) i += 1 # Add the remaining elements of arr2, if any while j < len(arr2): merged_array.append(arr2[j]) j += 1 return merged_array
Pointers and Comparison:
Appending Remaining Elements:
Consider merging two sorted arrays:
Array 1: [1, 3, 5, 7]
Array 2: [2, 4, 6, 8]
Step 1: Compare 1 and 2. Add 1 to the merged array → [1].
Step 2: Compare 3 and 2. Add 2 to the merged array → [1, 2].
Step 3: Compare 3 and 4. Add 3 to the merged array → [1, 2, 3].
Step 4: Compare 5 and 4. Add 4 to the merged array → [1, 2, 3, 4].
Step 5: Compare 5 and 6. Add 5 to the merged array → [1, 2, 3, 4, 5].
Step 6: Compare 7 and 6. Add 6 to the merged array → [1, 2, 3, 4, 5, 6].
Step 7: Compare 7 and 8. Add 7 to the merged array → [1, 2, 3, 4, 5, 6, 7].
Step 8: Only 8 remains, so add it to the merged array → [1, 2, 3, 4, 5, 6, 7, 8].
The merged array is now fully sorted: [1, 2, 3, 4, 5, 6, 7, 8].
Time Complexity: O(n + m), where n is the number of elements in the first array, and m is the number of elements in the second array. Each element from both arrays is processed exactly once.
Space Complexity: O(n + m), as the algorithm requires additional space to store the merged array.
Merge Sort:
Merging Data:
Efficient Search Algorithms:
Learning how to merge two sorted arrays is a fundamental skill that applies to many sorting algorithms and data manipulation tasks. This concept is not only central to understanding merge sort but also appears frequently in real-world applications where combining sorted data efficiently is necessary. By mastering this technique, you gain an essential tool for solving more complex algorithmic problems.
Topics Covered:
For more details and further examples, check out the full article on GeeksforGeeks: https://www.geeksforgeeks.org/merge-sort/.