Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Function merge.
- //Takes in two parameters: both int arrays, already each sorted.
- //Returns an array of int, which combines both parameter arrays sorted.
- public static int[] merge(..., ...)
- {
- //Declare two counter variables. I used 'ai' and 'bi'
- int ai = ...; int bi = ...;
- //We need to make the array that we're outputting.
- //What length does this array have?
- //Hint, all the input we have is array A and B.
- //How does our result's length depend on A and B?
- int length = ...;
- int[] result = ...;
- //Instead of doing counter i j k and incrementing k a whole bunch,
- // let's use a FOR loop to sequence through.
- //What does the FOR loop go through?
- // The FOR loop with build our result one piece at a time, and its
- // max size will be (you answer).
- for(...)
- {
- //If our counters ai and bi correspond to values
- // still in range of array A and B respectively,
- // then all we need to do is compare A[ai] to B[bi]
- // and choose whichever is lesser.
- //Then increment the ai or bi counter as appropriate.
- if(...)
- {
- if(...)
- {
- ...
- }
- else
- {
- ...
- }
- }
- else
- //If our counter A[ai] or B[bi] correspond to values out of range,
- // then we just need to check which is out of range.
- // Hint: use array.length instead of trying to lookup. You don't want OutOfBoundsException.
- //If A[ai] is out of range, use B[bi]. Vice versa.
- // Why is it guaranteed that A[ai] and B[bi] will never BOTh be out of range?
- {
- if(...)
- {
- ...
- }
- else
- {
- ...
- }
- }
- }
- return ...;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement