🎓 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 (178K+ 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]
Explanation
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment