Package com.zken.test;/** * @author Iamzken * 2015-8-28 * Merge two ordered arrays * */public class Sorter2 {public static void Merge2sort Edarray (int[] A, int[] B, int[] c) {//a array's current index int i = 0;//b array's current index int j = 0;//c The current index of the array int k = 0;//loop, as long as a and B are not traversed, they always loop whil E (i < a.length && J < b.length) {//If the current A[i] is smaller than b[j], set the c[k] element to A[i] and k++,i++if (A[i] < b[j]) {c[k++] = a[i++ ];//Otherwise, if the current a[i] is larger than b[j], the c[k] element is set to B[j], and k++,j++}else{c[k++] = b[j++];}} The last loop can end, stating that A has been cycled or B has been cycled///The following two loops can only have one satisfying cycle condition//As long as a does not cycle, put the remaining elements of a into C while (I < a.length) {c[k++] = a[i++];} As long as B is not finished, the remaining elements in B are placed in C while (J < b.length) {c[k++] = b[j++];}} Test program public static void Main (string[] args) {//To merge array aint[] A = new int[]{1,3,5,7,9};//to be merged array bint[] b = new int[]{2,4,6,8}; C used to hold the merged array int[] C = new Int[a.length+b.length];merge2sortedarray (A, B, c); for (int i = 0;i < c.length;i++) {SYSTEM.O Ut.print (c[i]+ "\ t");}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm research merge two sorted arrays Java edition