does not introduce a new array, implements the array element Exchange position function

Source: Internet
Author: User

Recently encountered a C + + face test. The requirement not to introduce a new array, to implement the array element Exchange position function, seems quite simple, but it took me a lot of time. Recorded here. Give us a simple idea. The specific requirements of the topic are:

does not introduce a new array. Implements an array element exchange position function: void swap (int a[], int m, int n), for example. Set M to 3,n for 4. The data in A is: 1 2 3 4 5 6 7. After the function is run, the data in A is: 4 5 6 7 1 2 3.

The key here is not to introduce new arrays and try to use fewer extra variables. My idea is to use the "Flashback tracking" method, which uses an extra variable to make two-number swaps.

Paste the code. What better way to communicate with you.

#include <iostream>
#include <unistd.h>

using namespace Std;

int judge_pos (int i,int m,int N)
{
    if (i>=0 && i<m)
    {
        return i+n;
   }
    Else if (i>=m && i< (m+n))
    {
         return i-m;
   }
    Else
    {
        return-1;
   }
}
int main ()
{
    int num_of_data;
    int i_array[1024];
    int m,n;

cout << "How many numbers does you want to input:";
Cin >> Num_of_data;
cout << "Input the Numbers,separate with space:" << Endl;
for (int i=0;i<num_of_data;i++)
{
CIN >> I_array[i];
}
cout << "Input m and n,separate with space. "<< Endl;
CIN >> m >> N;

int i = 0;
while (i_array[i]>=0)
{
for (int j=0;j< (m+n); j + +)
{
if (Judge_pos (j,m,n) ==i)
{

if (i_array[j]>0)
{
int temp = I_array[i];
I_array[i] =-i_array[j];
I_ARRAY[J] = temp;
I=j;
Break
}
Else
{
I_array[i] *= (-1);
I=j;
Break
}

}
}
}
for (int i=0;i<num_of_data;i++)
{
if (i< (m+n))
{
I_array[i] *= (-1);
}
cout << I_array[i] << "";
}
return 0;
}

does not introduce a new array, implements the array element Exchange position function

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.