|
| 1 | +package arrays; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/* |
| 6 | + * Problem :- |
| 7 | + * Merge two sorted array without using extra space |
| 8 | + */ |
| 9 | + |
| 10 | +/* |
| 11 | + * Understanding of the Problem :- |
| 12 | + * |
| 13 | + * We are given two sorted array. |
| 14 | + * We need to merge these two arrays, |
| 15 | + * such that the initial numbers(after complete sorting) are in the first array , |
| 16 | + * and the remaining numbers are in the second array. |
| 17 | + * Extra space allowed in O(1). |
| 18 | + */ |
| 19 | + |
| 20 | +/* |
| 21 | + * Simple Discussion : |
| 22 | + * This task is simple and O(m+n) if we are allowed to use extra space. |
| 23 | + * But it becomes really complicated when extra space is not allowed, |
| 24 | + * and doesn't look possible in less than O(m*n) worst case time. |
| 25 | + */ |
| 26 | + |
| 27 | +/* |
| 28 | + * Idea or Approach of Solution :- |
| 29 | + * The idea is to begin from last element of ar2[] and search it in ar1[]. |
| 30 | + * If there is a greater element in ae1[], then we moe lastt element of ar2[] at correct place in ar1[]. |
| 31 | + * |
| 32 | + * We can use INSERTION Sort type of insertion for this. |
| 33 | + */ |
| 34 | + |
| 35 | +public class Array_Problem_12 { |
| 36 | + |
| 37 | + static int[] arr1 = new int[] {1, 5 , 9, 10, 15, 20}; |
| 38 | + static int[] arr2 = new int[] {2, 3, 8, 13}; |
| 39 | + |
| 40 | + static void merge(int m , int n) { |
| 41 | + |
| 42 | + //Iterate through all elements of the last element |
| 43 | + for(int i = n-1; i >= 0; i--) { |
| 44 | + |
| 45 | + /* |
| 46 | + * FInd the smallest element greater than ar2[i]. |
| 47 | + * Move all elements one position ahead till the smallest greater element is not found. |
| 48 | + */ |
| 49 | + int j , last = arr1[m -1]; |
| 50 | + for( j = m-2 ; j>= 0 && arr1[j] > arr2[i] ; j--) |
| 51 | + arr1[j+1] = arr1[j]; |
| 52 | + |
| 53 | + //if there was a greater element |
| 54 | + if(j != m-2 || last > arr2[i]) { |
| 55 | + arr1[j+1] = arr2[i]; |
| 56 | + arr2[i] = last; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public static void main(String[] args) { |
| 62 | + merge(arr1.length, arr2.length); |
| 63 | + System.out.println("After Merging nFirst Array: "); |
| 64 | + System.out.println(Arrays.toString(arr1)); |
| 65 | + System.out.println("Second Array: "); |
| 66 | + System.out.println(Arrays.toString(arr2)); |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments