Junior — Middle
Kuidas ühendada kaks sorteeritud massiivi üheks, säilitades elementide järjekorra?
sobes.tech AI
Vastus AI-lt
To merge two sorted arrays into one sorted array, you can use a merge algorithm similar to the one used in merge sort. The idea is to traverse both arrays simultaneously, compare the current elements, and add the smaller one to the resulting array.
Example in Go:
func mergeSortedArrays(a, b []int) []int {
result := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
result = append(result, a[i])
i++
} else {
result = append(result, b[j])
j++
}
}
// Add remaining elements
result = append(result, a[i:]...)
result = append(result, b[j:]...)
return result
}
This method runs in O(n + m) time, where n and m are the sizes of the original arrays.