📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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]
Comments
Post a Comment
Leave Comment