MergeSortedArrays

Run Settings
LanguageGo
Language Version
Run Command
package main import ( "fmt" ) // 2 sorted inputs // [0, 2, 3], [4, 6, 10] => [0, 2, 3, 4, 6, 10] // [0, 2, 3], [2, 6, 10] => [0, 2, 2, 4, 6, 10] // NOTE: can refactor the if blocks into a separate functions. func MergeSortedArrays (arr1, arr2 []int) []int { if (len(arr1) == 0) { return arr1 } else if (len(arr2) == 0) { return arr2 } // start with an empty array var merged []int i := 0 j := 0 // iterate through the first array for i < len(arr1) { if (j == len(arr2)) { merged = append(merged, arr1[i:]...) break } // compare elements of first array with the first item of the second array if (arr1[i] <= arr2[j]) { merged = append(merged, arr1[i]) i++ } else { // if element in second array is larger, then add it and increment the counte merged = append(merged, arr2[j]) j++ } } merged = append(merged, arr2[j:]...) return merged } func main() { fmt.Println(MergeSortedArrays([]int{2,3,6}, []int{1,2})) }
Editor Settings
Theme
Key bindings
Full width
Lines