Merge Sorted Array
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Thoughts:
A direct solution is, allocate an array with length [m+n] and merge. Then copy the merged array to the original array A. I strongly doubt if it would be the expected answer.
Let's assume only O(1) space could be used instead. Then we have to consider the exploit of excess space in array A, with length n. We can merge the two arrays there, and when the space is all used up, data at starting of A should be either useless (already merged) or at the right place (if all elements in B are smaller than A).
Then we rotate the array leftwise by m. Such coding can be implemented by three reverses: [0, m+n), [0, n), [n, m+n). This is illustrated in Programming Pearls.
Solution:
- class Solution {
- public:
- void merge(int A[], int m, int B[], int n) {
- // Iterator used through merging
- int merge_A = 0;
- int merge_B = 0;
- // merge is done at the end of m-th element, A[]
- int merge_iter = m;
- while(merge_A < m || merge_B < n)
- {
- // check if we reached the end of merge region, if so,
- // start from beginning
- if (merge_iter == m + n)
- merge_iter = 0;
- if (merge_A == m) // merge A is done
- A[merge_iter++] = B[merge_B++];
- else if (merge_B == n) // merge B is done
- A[merge_iter++] = A[merge_A++];
- else
- A[merge_iter++] = (A[merge_A] < B[merge_B] ? A[merge_A++] : B[merge_B++]);
- }
- // merge is complete, now the array looks like
- // 4567 | 123
- // so we need to reverse it -- ref. Programming Pearls
- reverse(A, A+m);
- reverse(A+m, A+m+n);
- reverse(A, A+m+n);
- }
- };
No comments:
Post a Comment