Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class MergeSort_Algo_merge {
- public static void main(String[] args)
- {
- int[] ary001_sorted = new int[] {9, 20, 100, 300};
- int[] ary002_sorted = new int[] {3, 10, 11, 201};
- int[] merge = merge(ary001_sorted, ary002_sorted);
- printArray(merge);
- }
- // imagine you are at the last step of mergesort when you are coming from the bottom up.
- // Therefore, the array with size 1 is sorted; then up and the arrays with size 2 will be sorted too.
- // Here, we are simulating a up-k layers, and now we have two sorted sub-arrays to be merged.
- private static int[] merge(int[] aryLeft, int[] aryRight){
- if (aryLeft.length == 0) return aryRight;
- if (aryRight.length == 0) return aryLeft;
- int[] result = null;
- if (aryLeft[0] <= aryRight[0]) { // if smaller, extract it out in this layer
- result = concat(subArray(aryLeft, 0, 1) , merge(subArray(aryLeft, 1, aryLeft.length), aryRight)) ;
- }else {
- result = concat(subArray(aryRight, 0, 1) , merge(aryLeft, subArray(aryRight, 1, aryRight.length))) ;
- }
- return result;
- }
- private static int[] concat(int[] first, int[] second){
- int[] both = Arrays.copyOf(first, first.length + second.length);
- System.arraycopy(second, 0, both, first.length, second.length);
- return both;
- }
- private static int[] copyArray(int[] array){
- return subArray(array, 0, array.length);
- }
- public static int[] subArray(int[] array, int beg, int end) {
- return Arrays.copyOfRange(array, beg, end);
- }
- private static void printArray(int[] ary){
- for (int i = 0; i < ary.length; i++) {
- System.out.printf("%4d" , ary[i]);
- }
- System.out.println();
- }
- private static void print2DArray(int[][] ary){
- for (int i = 0; i < ary.length; i++) {
- for (int j = 0; j < ary[i].length; j++) {
- System.out.printf("%4d" , ary[i][j]);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement