Algorithm research merge two sorted arrays Java edition

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.