Advertisement
teleias

Merge

Feb 16th, 2015
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. //Function merge.
  2.     //Takes in two parameters: both int arrays, already each sorted.
  3.     //Returns an array of int, which combines both parameter arrays sorted.
  4.     public static int[] merge(..., ...)
  5.     {
  6.         //Declare two counter variables. I used 'ai' and 'bi'
  7.         int ai = ...; int bi = ...;
  8.         //We need to make the array that we're outputting.
  9.         //What length does this array have?
  10.         //Hint, all the input we have is array A and B.
  11.         //How does our result's length depend on A and B?
  12.         int length = ...;
  13.         int[] result = ...;
  14.         //Instead of doing counter i j k and incrementing k a whole bunch,
  15.         // let's use a FOR loop to sequence through.
  16.         //What does the FOR loop go through?
  17.         // The FOR loop with build our result one piece at a time, and its
  18.         //  max size will be (you answer).
  19.         for(...)
  20.         {
  21.             //If our counters ai and bi correspond to values
  22.             // still in range of array A and B respectively,
  23.             // then all we need to do is compare A[ai] to B[bi]
  24.             // and choose whichever is lesser.
  25.             //Then increment the ai or bi counter as appropriate.
  26.             if(...)
  27.             {
  28.                 if(...)
  29.                 {
  30.                     ...
  31.                 }
  32.                 else
  33.                 {
  34.                     ...
  35.                 }
  36.             }
  37.             else
  38.             //If our counter A[ai] or B[bi] correspond to values out of range,
  39.             // then we just need to check which is out of range.
  40.             // Hint: use array.length instead of trying to lookup. You don't want OutOfBoundsException.
  41.             //If A[ai] is out of range, use B[bi]. Vice versa.
  42.             // Why is it guaranteed that A[ai] and B[bi] will never BOTh be out of range?
  43.             {
  44.                 if(...)
  45.                 {
  46.                     ...
  47.                 }
  48.                 else
  49.                 {
  50.                     ...
  51.                 }
  52.             }
  53.            
  54.         }
  55.         return ...;
  56.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement