careercup-Sorting and finding 11.1

Source: Internet
Author: User

11.1 Given two sorted arrays A and B, where the end of a has enough buffer space to accommodate B. Write a method that merges B into a and sorts.

Solution:

There is enough buffering at the end of the known quantity Group A, no additional space is required. The process logic of a program is simple, which is to compare the elements in A and b one by one, and insert the array sequentially until all the elements in A and B are exhausted. The only problem with this is that if you insert an element into the front of the array A, you must move the original element back to make room. A better practice is to insert elements into the end of array A, where free space is available.

The following code implements this practice, starting with the end elements of arrays A and B, and placing the largest elements at the end of the array A.

C + + Implementation code:

#include <iostream>using namespacestd;voidMergeintA[],intB[],intLasta,intLastb) {    inti=lasta-1; intj=lastb-1; intk=lasta+lastb-1;  while(i>=0&&j>=0)    {        if(a[i]>B[j]) {A[k--]=a[i--]; }        Else{a[k--]=b[j--]; }    }     while(j>=0) {a[k--]=b[j--]; }}intMain () {inta[ -]={1,3,5,7,9}; intb[7]={2,4,6,8,Ten, One, the}; Merge (A, B,5,7);  for(auto t:a) cout<<t<<' '; cout<<Endl;}

careercup-Sorting and finding 11.1

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.