Integer Array Processing Algorithm (6) merge two Arrays

Source: Internet
Author: User

To merge the elements in the two arrays to the integer array c, you must remove the repeated elements and keep the c order (non-descending ).
Example:
A = 2, 3, 4, 6, 8, 9
B = 7,9, 10

// Merge two ordered arrays void Merge (int * a, int * B, int * c, int nA, int nB, int & nCout) containing nA and nB elements) {int I = 0; int j = 0; int k = 0; while (I <nA & j <nB) {if (a [I] <B [j]) // If the element of a is small, insert the element in a to c {c [k ++] = a [I]; ++ I; nCout ++ ;} else if (a [I] = B [j]) // if elements a and B are equal, you can insert both, insert a {c [k ++] = a [I]; ++ I; ++ j; nCout ++ ;} else // a [I]> B [j] // If the element in B is small, insert the element in B to c {c [k ++] = B [j]; ++ j; nCout ++ ;}} if (I = nA) // if traversal of a is complete, process the remaining elements of B {for (int m = j; m <nB; ++ m) {c [k ++] = B [m]; nCout ++ ;}} else // j = n. If B is traversed, process the remaining elements in a {for (int m = I; m <nA ;++ m) {c [k ++] = a [m]; nCout ++ ;}}}

The test code is as follows:

int main(){int* a= new int[6];int* b= new int[3];a[0]=2;a[1]=3;a[2]=4;a[3]=6;a[4]=8;a[5]=9;b[0]=7;b[1]=9;b[2]=10;int nOut = 0;int* output = new int[12];Merge(a, b, output, 6, 3, nOut);for (int i=0; i<nOut; i++){cout << output[i] << "," ;}cout << endl;delete[] a;a=NULL;delete[] b;b=NULL;delete[] output;output=NULL;cout << endl;return 0;}

Test results:

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.