Java Program to Merge Two Arrays Without Extra Space

Combining items of two arrays in place is a common difficulty when merging them without requiring extra space. To ensure that elements from both arrays are sorted and arranged correctly without requiring the use of an additional array for storage, this requires careful manipulation.

Method 1: Gap Method (Shell Sort Based)

A practical method for combining two sorted arrays in one location is the gap method. The plan is to compare items using a gap and shift them around till the gap is as small as zero.

Steps

  1. First, set the gap equal to the total of the two arrays' lengths.
  2. Then, use the formula gap = (gap + 1) / 2 to keep the gap from growing.
  3. If items are out of sequence, compare them at the gaps between them and swap them.
  4. Complete the last comparison after repeating the procedure until the distance equals one.

Let's implement the above steps in a Java program.

File Name: MergeWithoutExtraSpace.java

Output:

 
First Array: 1 2 3 4 7 
Second Array: 8 9 10   

Method 2: Insertion Method

In this method, we iterate through the first array and inserting elements from the second array into the appropriate locations. Although this approach may be less practical than the Gap Method, it may be more intuitive.

Steps

  1. Traverse the first array starting at the end.
  2. Verify whether the final element in the second array is higher for each element.
  3. If so, switch the elements around and arrange the more significant elements in the first array's proper location.

Let's implement the above steps in a Java program.

File Name: MergeWithoutExtraSpace.java

Output:

 
First Array: 1 2 3 4 7 
Second Array: 8 9 10   

Method 3: Two-Pointer Technique

Another effective method for merging arrays without requiring more space is the Two-pointer Technique. Two pointers, each referring to the current element of the arrays being merged, must be kept up to date.

Steps

  1. One pointer should be initialised for each array.
  2. Examine the items that the points point to.
  3. If needed, switch and adjust the pointers as required.
  4. Continue until every component is in position.

Let's implement the above steps in a Java program.

File Name: MergeWithoutExtraSpace.java

Output:

 
First Array: 1 2 3 4 7 
Second Array: 8 9 10   

Conclusion

In this section, we have discussed various ways to merge two arrays without requiring more space, including the Insertion Method, the Gap Method, and the Two-pointer Technique.

Every approach has its own benefits and can be selected according to the particular needs and limitations of the given task. The Java code samples that are provided show how to use these methods to combine two sorted arrays in real-time.