Skip to content

Commit 0f01c9e

Browse files
authored
Merge pull request #1247 from harshitcompcode/patch-2
Create Merge_Sorted_array.go
2 parents c419b96 + a6c6c14 commit 0f01c9e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Arrays/Merge_Sorted_array.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
Example:
2+
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
3+
Output: [1,2,2,3,5,6]
4+
5+
Here's an implementation in Go to merge two sorted arrays:
6+
7+
func merge(nums1 []int, m int, nums2 []int, n int) {
8+
i := m - 1 // Index of last element in nums1
9+
j := n - 1 // Index of last element in nums2
10+
11+
// Merge from the end of the arrays to avoid overwriting
12+
for k := m + n - 1; k >= 0; k-- {
13+
if j < 0 {
14+
// No more elements in nums2, nums1 already sorted
15+
return
16+
}
17+
if i >= 0 && nums1[i] > nums2[j] {
18+
nums1[k] = nums1[i]
19+
i--
20+
} else {
21+
nums1[k] = nums2[j]
22+
j--
23+
}
24+
}
25+
}
26+
27+
The merge function takes in two sorted arrays nums1 and nums2, where nums1 has m elements and nums2 has n elements.
28+
The function then merges nums2 into nums1 in-place, resulting in a single sorted array.
29+
30+
Starting from the end of both arrays, the function compares the last elements of nums1 and nums2,
31+
and puts the larger one at the end of nums1. This process continues until all elements in nums2 have been merged into nums1.
32+
33+
Note that since nums1 has enough space to accommodate all elements, we don't need to create a new array to store the merged elements.
34+
We can just overwrite the 0 elements at the end of nums1 with the merged elements.

0 commit comments

Comments
 (0)