Merge Two Sorted Arrays
This Go program merges two sorted arrays into a single sorted array. The program assumes that the input arrays are already sorted in non-decreasing order. The output will be a new array containing all elements from the two input arrays, sorted in non-decreasing order.
Program Structure
- Main Function: The main function contains the logic to merge two sorted arrays.
- Merge Function: A separate function to perform the merging of two sorted arrays.
Go Code
package main import "fmt" // mergeSortedArrays merges two sorted arrays into a single sorted array. func mergeSortedArrays(array1, array2 []int) []int { mergedArray := make([]int, len(array1)+len(array2)) i, j, k := 0, 0, 0 // Merge arrays while there are elements in both arrays for i < len(array1) && j < len(array2) { if array1[i] <= array2[j] { mergedArray[k] = array1[i] i++ } else { mergedArray[k] = array2[j] j++ } k++ } // Copy remaining elements of array1, if any for i < len(array1) { mergedArray[k] = array1[i] i++ k++ } // Copy remaining elements of array2, if any for j < len(array2) { mergedArray[k] = array2[j] j++ k++ } return mergedArray } func main() { array1 := []int{1, 3, 5, 7} array2 := []int{2, 4, 6, 8} mergedArray := mergeSortedArrays(array1, array2) fmt.Println("Merged Array:", mergedArray) }
Explanation
The program consists of the following parts:
- mergeSortedArrays Function: This function takes two sorted arrays as input and returns a new array that is the result of merging the two input arrays. It uses three indices:
- i: Tracks the current position in the first array.
- j: Tracks the current position in the second array.
- k: Tracks the current position in the merged array.
The function compares elements from both arrays and inserts the smaller element into the merged array. It continues this process until all elements from one of the arrays have been added to the merged array. It then adds any remaining elements from the other array.
- Main Function: The main function initializes two sorted arrays, calls the mergeSortedArrays function, and prints the merged array to the console.
Output
When the program is executed, it will output the merged array:
Merged Array: [1, 2, 3, 4, 5, 6, 7, 8]