Data structure Learning-array a[m+n] in turn two linear tables (A1,A2 AM), (b1,b2 bn), swap the two sequential table positions

Source: Internet
Author: User

Swaps the two sequential table positions in the array, which will be (b1,b2 bn) put to (A1,a2 AM) front.

Solution One:

Adds all the elements in the array (a1,a2, am,b1,b2, bn) in-situ inversion (bn,bn-1, B1,am,am-1 A1), the first n elements and the rear m elements are respectively reversed, resulting (b1,b2 BN,A1,A2 AM) to achieve position interchangeability.

Code:

voidReverse (intA[],intLeftintRightintarraySize) {//reversal (aleft,aleft+1,aleft+2,aright) for (aright,aright-1,,aleft)    if(Left>=right| | right>=arrysize)return; intMid= (left+right)/2;  for(intI=0; i<=mid-left;i++)    {        inttemp=a[left+i]; A[left+i]=a[right-i]; A[right-i]=temp; }}        voidExchange (intA[],intMintNintarraySize) {Reverse (A,0, m+n-1, arrysize); Reverse (A,0, N-1, arrysize); Reverse (A,n,m+n-1, arrysize); }

Solution Two:

Implemented with auxiliary arrays.

To create an array of size m, the first m integers in a are temporarily present in S, while the last n elements in a are shifted to the left, and then the staged in S is placed back in a subsequent cell in a.

 void  Exchange (int  a[],int  m,int   N) { 
   
    int  
     s[m],i;  
    for  (I=
    0 ; i<m;i++) 
    // 
     Save the first m to S  s[i]=
    a[i];  
    for  (I=
    0 ; i<n;i++) 
    // 
     move back N to front  a[i]=a[m+
    i];  
    for  (I=
    0 ; i<m;i++) 
    // 
     Insert the scratch in S in the back  a[n+i]=
    s[ I];}  
   

Data structure Learning-array a[m+n] in turn two linear tables (A1,A2 AM), (b1,b2 bn), swap the two sequential table positions

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.