Advertisement
uopspop

Untitled

Sep 13th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class MergeSort_Algo_merge {
  4.     public static void main(String[] args)
  5.     {
  6.         int[] ary001_sorted = new int[] {9, 20, 100, 300};
  7.         int[] ary002_sorted = new int[] {3, 10, 11, 201};
  8.         int[] merge = merge(ary001_sorted, ary002_sorted);
  9.         printArray(merge);
  10.     }
  11.  
  12.     // imagine you are at the last step of mergesort when you are coming from the bottom up.
  13.     // Therefore, the array with size 1 is sorted; then up and the arrays with size 2 will be sorted too.
  14.     // Here, we are simulating a up-k layers, and now we have two sorted sub-arrays to be merged.
  15.     private static int[] merge(int[] aryLeft, int[] aryRight){
  16.         if (aryLeft.length == 0) return aryRight;
  17.         if (aryRight.length == 0) return aryLeft;
  18.  
  19.         int[] result = null;
  20.         if (aryLeft[0] <= aryRight[0]) { // if smaller, extract it out in this layer
  21.             result = concat(subArray(aryLeft, 0, 1) , merge(subArray(aryLeft, 1, aryLeft.length), aryRight)) ;
  22.         }else {
  23.             result = concat(subArray(aryRight, 0, 1) , merge(aryLeft, subArray(aryRight, 1, aryRight.length))) ;
  24.         }
  25.         return result;
  26.     }
  27.  
  28.  
  29.     private static int[] concat(int[] first, int[] second){
  30.         int[] both = Arrays.copyOf(first, first.length + second.length);
  31.         System.arraycopy(second, 0, both, first.length, second.length);
  32.         return both;
  33.     }
  34.  
  35.     private static int[] copyArray(int[] array){
  36.         return subArray(array, 0, array.length);
  37.     }
  38.  
  39.     public static int[] subArray(int[] array, int beg, int end) {
  40.         return Arrays.copyOfRange(array, beg, end);
  41.     }
  42.  
  43.     private static void printArray(int[] ary){
  44.         for (int i = 0; i < ary.length; i++) {
  45.             System.out.printf("%4d" , ary[i]);
  46.         }
  47.         System.out.println();
  48.     }
  49.     private static void print2DArray(int[][] ary){
  50.         for (int i = 0; i < ary.length; i++) {
  51.             for (int j = 0; j < ary[i].length; j++) {
  52.                 System.out.printf("%4d" , ary[i][j]);
  53.             }
  54.             System.out.println();
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement