Here you can find the source of merge(int[] a, int[] b)
Parameter | Description |
---|---|
a | sorted array. |
b | sorted array. |
public static int[] merge(int[] a, int[] b)
//package com.java2s; //License from project: Apache License public class Main { /**/*from ww w . ja v a2 s. c om*/ * Merges two sorted arrays to a single new array. * * @param a sorted array. * @param b sorted array. * @return a new array that merged both into a new sorted array. */ public static int[] merge(int[] a, int[] b) { int[] toReturn = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a[i] < b[j]) { toReturn[k] = a[i]; i++; } else { toReturn[k] = b[j]; j++; } k++; } System.arraycopy(a, i, toReturn, k, a.length - i); System.arraycopy(b, j, toReturn, k + a.length - i, b.length - j); return toReturn; } /** * Merges two sorted subparts of the given number array. E.G: if you want to * merge { 1, 2, 5, 3, 5, 6, 7 } you have to pass merge(concat, 0, 2, 6), * because you are starting at zero, the second sorted array begins at index * 3, so it is 3-1=2. The end is the length of the array - 1. * * @param numbers the array which has two sorted sub arrays. * @param startIndexA the start index of the first sorted array. * @param endIndexA the end index of the first sorted array. * @param endIndexB the end of the second array. */ public static void merge(int[] numbers, int startIndexA, int endIndexA, int endIndexB) { int[] toReturn = new int[endIndexB - startIndexA + 1]; int i = 0, k = startIndexA, j = endIndexA + 1; while (i < toReturn.length) { if (numbers[k] < numbers[j]) { toReturn[i] = numbers[k]; k++; } else { toReturn[i] = numbers[j]; j++; } i++; // if we hit the limit of an array, copy the rest if (j > endIndexB) { System.arraycopy(numbers, k, toReturn, i, endIndexA - k + 1); break; } if (k > endIndexA) { System.arraycopy(numbers, j, toReturn, i, endIndexB - j + 1); break; } } System.arraycopy(toReturn, 0, numbers, startIndexA, toReturn.length); } }