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