Introduction
In programming, merging arrays is a common operation, especially when working with algorithms like the merge sort. When given two sorted arrays, the challenge lies in efficiently combining them while maintaining their sorted order. In this blog post, we will walk you through a Go program that achieves this task.
Program Overview
Our program will be structured in the following manner:
Input: Two sorted arrays.
Processing: A merging process where we combine both arrays, ensuring that the resulting array remains sorted.
Output: One merged, sorted array.
Code Program
package main
import "fmt"
// Function to merge two sorted arrays.
func mergeSortedArrays(arr1, arr2 []int) []int {
mergedArray := make([]int, len(arr1)+len(arr2))
i, j, k := 0, 0, 0
// Traverse both arrays and insert smaller value from arr1 or arr2
// into mergedArray and then move the pointer of that array.
for i < len(arr1) && j < len(arr2) {
if arr1[i] < arr2[j] {
mergedArray[k] = arr1[i]
i++
} else {
mergedArray[k] = arr2[j]
j++
}
k++
}
// If there are remaining elements in arr1, copy them.
for i < len(arr1) {
mergedArray[k] = arr1[i]
i++
k++
}
// If there are remaining elements in arr2, copy them.
for j < len(arr2) {
mergedArray[k] = arr2[j]
j++
k++
}
return mergedArray
}
// Main function to execute the program.
func main() {
array1 := []int{1, 3, 5, 7}
array2 := []int{2, 4, 6, 8, 10}
merged := mergeSortedArrays(array1, array2)
fmt.Println("Merged Sorted Array:", merged)
}
Output:
Merged Sorted Array: [1 2 3 4 5 6 7 8 10]
Explanation
Function Declaration: The mergeSortedArrays function is where the magic happens. It takes in two sorted integer arrays (arr1 and arr2) as parameters.
Merging Logic: We first create an empty mergedArray of length equal to the sum of lengths of arr1 and arr2. We then use three pointers (i, j, and k) to traverse arr1, arr2, and mergedArray, respectively. We compare values from arr1 and arr2 and insert the smaller value into mergedArray.
Handling Leftover Elements: After the initial merging, if any elements are left in either arr1 or arr2, we append them to the mergedArray since they would already be in the sorted order.
Main Function: Here, we define our two sorted arrays and call the mergeSortedArrays function to get the merged result. The final merged array is then printed to the console.
By following this approach, our Go program efficiently merges two sorted arrays, ensuring the result is also sorted. This serves as a foundational concept in the world of algorithms and is immensely useful in real-world data processing tasks.
Comments
Post a Comment
Leave Comment