Access over 35 million academic & study documents

3 Way Array MergeWrite a method called threeWayMerge in Java that

Content type
User Generated
Showing Page:
1/2
3-Way Array Merge
Write a method called threeWayMerge in Java that has the
following signature:
int[ ] threeWayMerge (int[ ] a, int [ ] b, int [ ] c)
The method will accept three sorted arrays a, b, c and
return a sorted array d which will contain all the elements
of the three input arrays in sorted order. The running time
must be O(N) where N is the combined length of the three
arrays.
Thank you!
Solution
public int[] threeWayMerge(int[] a, int[] b, int[] c) { if
(a == null || b == null || c == null) { return null;
} int[] res = new int[a.length + b.length + c.length];
System.arraycopy(a, 0, res, 0, a.length);
twoWayMerge(res, a.length, b); twoWayMerge(res,
a.length + b.length, c); return res; } public void
twoWayMerge(int[] large, int count, int[] small) { int
p1 = count - 1; int p2 = small.length - 1; int last
= count + small.length - 1; while (p1 >= 0 && p2 >= 0)
{ large[last--] = large[p1] > small[p2] ? large[p1-
-] : small[p2--]; } if (p2 >= 0) {
System.arraycopy(small, 0, large, 0, p2 + 1); } }

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/2

Sign up to view the full document!

lock_open Sign Up
Unformatted Attachment Preview
3-Way Array Merge Write a method called threeWayMerge in Java that has the following signature: int[ ] threeWayMerge (int[ ] a, int [ ] b, int [ ] c) The method will accept three sorted arrays a, b, c and return a sorted array d which will contain all the elements of the three input arrays in sorted order. The running time must be O(N) where N is the combined length of the three arrays. Thank you! Solution public int[] threeWayMerge(int[] a, int[] b, int[] c) { (a == null || b == null || c == null) { } if return null; int[] res = new int[a.length + b.length + c.length]; System.arraycopy( ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.
Studypool
4.7
Indeed
4.5
Sitejabber
4.4