Merge Sorted Array C++ Code

To merge two sorted arrays nums1 and nums2 into nums1, we can use a two-pointer approach. We will start with two pointers p1 and p2, initialized to the last valid element in nums1 and nums2 respectively. We will compare the elements at these pointers and copy the larger one to the end of nums1. We will then decrement the pointer that held the larger element. We will continue this process until we have merged all the elements from nums2 into nums1.

Here is the implementation for the merge function:

These lines initialize three pointers p1, p2, and p3. p1 is initialized to the last index of the non-zero elements in nums1, p2 is initialized to the last index of nums2, and p3 is initialized to the last index of the merged array.

This line starts a while loop that continues until either p1 or p2 becomes negative.

Within the while loop, this code compares the values at the current positions of p1 and p2. If the value at p1 is greater than the value at p2, then the value at p1 is copied to the current position of p3, and p1 is decremented. Otherwise, the value at p2 is copied to the current position of p3, and p2 is decremented. In either case, p3 is also decremented.

After the first while loop ends, if there are any remaining elements in nums2, this code copies them to the remaining positions in nums1. This while loop continues until p2 becomes negative. Within the loop, each element at nums2[p2] is copied to nums1[p3], and both p2 and p3 are decremented.The above code implements the merging of two sorted arrays nums1 and nums2 into nums1, using a two-pointer approach.

Did you find this article valuable?

Support Bandari sai kumar by becoming a sponsor. Any amount is appreciated!