Monday 19 June 2023

How to Merge two sorted arrays without using extra space?

To merge two sorted arrays without using extra space, please follow the below steps:

  1. You can utilize the fact that both arrays are already sorted. 
  2. You can perform an in-place merge by rearranging the elements in one of the arrays. 
  3. Start from the last elements of both arrays and compare them.
  4. Place the larger number at end of first array.
  5. Decrease both the array index and move to the previous position.
  6. Continue this process until all elements are processed.
  7. if anything left in 2nd array then copy it at last of 1st array.

1
java
public class MergeSortedArrays {
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // index of last element in nums1 
int j = n - 1; // index of last element in nums2
int k = m + n - 1; // index of last position in merged array // Starting from the last elements of both arrays and comparing them 
while (i >= 0 && j >= 0) { 
if (nums1[i] >= nums2[j]) { 
 nums1[k] = nums1[i]; i--;
 } else
 nums1[k] = nums2[j]; j--; 
 } 
 k--; 
 } 
// If there are remaining elements in nums2, copy them to nums1
while (j >= 0) {
nums1[k] = nums2[j]; j--; k--; 
 } 
 } 
public static void main(String[] args)
int[] nums1 = {1, 3, 5, 0, 0, 0}; // sorted array with extra space for merging 
int[] nums2 = {2, 4, 6}; // sorted array 
int m = 3; // number of elements in nums1 
int n = 3; // number of elements in nums2 
 merge(nums1, m, nums2, n); // Print the merged array 
for (int num : nums1) { 
 System.out.print(num + " "); 
 }
 }
 }

The output of the given example would be: `1 2 3 4 5 6`, which represents the merged sorted array. 

No comments:

Post a Comment