Skip to content

Commit 24fb984

Browse files
committed
Add new programs
1 parent 91e2413 commit 24fb984

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Diff for: mypc/main/java/Merge2SortedArrayInOne.java

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package main.java;
2+
3+
/**
4+
* Cracking the Coding Interview 10.1 Sorted Merge: You are given two sorted
5+
* arrays, A and B, where A has a large enough buffer at the end to hold B.
6+
* Write a method to merge B into A in sorted order.
7+
*
8+
* <p>
9+
* Since we know that A has enough buffer at the end, we won't need to allocate
10+
* additional space. Our logic should involve simply comparing elements of A and
11+
* B and inserting them in order, until we've exhausted all elements in A and in
12+
* B. The only issue with this is that if we insert an element into the front of
13+
* A, then we'll have to shift the existing elements backwards to make room for
14+
* it. It's better to insert elements into the back of the array, where there's
15+
* empty space. The code below does just that. It works from the back of A and
16+
* B, moving the largest elements to the back of A.
17+
* </p>
18+
*
19+
* Note that you don't need to copy the contents of A after running out of
20+
* elements in B. They are already in place.
21+
**/
22+
public class Merge2SortedArrayInOne {
23+
24+
private static void merge(int[] a, int[] b, int lastA, int lastB) {
25+
int indexA = lastA - 1; /* Index of last element in array a */
26+
int indexB = lastB - 1; /* Index of last element in array b */
27+
int indexMerged = lastB + lastA - 1; /* end of merged array */
28+
/* Merge a and b, starting from the last element in each */
29+
while (indexB >= 0) {
30+
/* end of a is > than end of b */
31+
if (indexA >= 0 && a[indexA] > b[indexB]) {
32+
a[indexMerged] = a[indexA]; // copy element
33+
indexA--;
34+
} else {
35+
a[indexMerged] = b[indexB]; // copy element
36+
indexB--;
37+
}
38+
indexMerged--; // move indices
39+
}
40+
}
41+
42+
private static void printArray(int[] arr) {
43+
for(int i=0;i<arr.length;i++) {
44+
System.out.print(arr[i]+" ");
45+
}
46+
System.out.println();
47+
}
48+
public static void main(String[] args) {
49+
int[] arrOne = {2,5,7,9,12,-1,-1,-1,-1};
50+
int[] arrTwo = {8,10,11,13};
51+
int lastArrOne = 5;
52+
merge(arrOne, arrTwo, lastArrOne, arrTwo.length);
53+
printArray(arrOne);
54+
}
55+
56+
}

0 commit comments

Comments
 (0)