27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 9 | Sorting <strong>and</strong> Searching<br />

9.1 You are given two sorted arrays, A <strong>and</strong> B, <strong>and</strong> A has a large enough buffer at <strong>the</strong> end<br />

to hold B. Write a method to merge B into A in sorted order.<br />

SOLUTION<br />

pg 66<br />

This code is a part of <strong>the</strong> st<strong>and</strong>ard merge-sort code. We merge A <strong>and</strong> B from <strong>the</strong> back, by<br />

comparing each element.<br />

1 public static void merge(int[] a, int[] b, int n, int m) {<br />

2 int k = m + n - 1; // Index of last location of array b<br />

3 int i = n - 1; // Index of last element in array b<br />

4 int j = m - 1; // Index of last element in array a<br />

5<br />

6 // Start comparing from <strong>the</strong> last element <strong>and</strong> merge a <strong>and</strong> b<br />

7 while (i >= 0 && j >= 0) {<br />

8 if (a[i] > b[j]) {<br />

9 a[k--] = a[i--];<br />

10 } else {<br />

11 a[k--] = b[j--];<br />

12 }<br />

13 }<br />

14 while (j >= 0) {<br />

15 a[k--] = b[j--];<br />

16 }<br />

17 }<br />

Note: You don’t need to copy <strong>the</strong> contents of a after running out of b’s. They are<br />

already in place.<br />

1 7 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!