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
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment