Merge Two Sorted Arrays without extra space

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//Merge 2 sorted Arrays where Bigger arrays have a space for smaller Array
//Example: arr1[] = {2,3,4,0,0,0,}
//arr2[] = {5,6,7} Array-2 size is 3, which can be places at array-1
import java.util.Arrays;

public class Merge2SortedArrays {

	public static void main(String[] args) {
		Merge2SortedArrays o = new Merge2SortedArrays();
		int[] arr1 = { 1, 2, 2, 13, 0, 0, 0, 0 };
		int[] arr2 = { 1, 3, 8, 9 };

		o.getSortedArray(arr1, arr2);

	}
	/*
	 * Taking array1(element) and array1(element) comparing if arr1 element is
	 * lesser to arr2 element increment if arr1 element is greater to arr2 element
	 * swap and sort array2
	 * 
	 * Now iterate throught the total array and place sorted 2nd array into 1st
	 * array an print
	 * 
	 */

	public void getSortedArray(int[] arr1, int[] arr2) {

		int arr1Begin = 0;
		int jarr2Begin = 0;
		int temp = 0;
		int findLength = (arr1.length) - arr2.length;
		System.out.println(findLength);
		for (int k = 0; k < findLength; k++) {
			if (arr1[arr1Begin] < arr2[jarr2Begin]) {
				arr1Begin++;
			}
			if (arr1[arr1Begin] >= arr2[jarr2Begin]) {
				temp = arr1[arr1Begin];
				arr1[arr1Begin] = arr2[jarr2Begin];
				arr2[jarr2Begin] = temp;
				arr1Begin++;
				Arrays.sort(arr2);
			}

		}
		System.out.println("1st sorted array: " + Arrays.toString(arr1));
		System.out.println("2nd array is: " + Arrays.toString(arr2));
		System.out.println("*********Merging 2 sorted Arrays**************");
		int temp1 = 0;
		int p = 0;
		for (int m = findLength; m < arr1.length; m++) {

			temp1 = arr1[findLength];
			arr1[findLength] = arr2[p];
			arr2[p] = temp1;
			p++;
			findLength++;

		}
		System.out.println("Final Sorted Array: " + Arrays.toString(arr1));
	}

}
Output: 1st sorted array: [1, 1, 2, 2, 0, 0, 0, 0] 2nd array is: [3, 8, 9, 13] *********Merging 2 sorted Arrays************** Final Sorted Array: [1, 1, 2, 2, 3, 8, 9, 13]

No comments:

Post a Comment