# 面试题：移动数组的元素

5
2 6 15 39 5
3

15 39 5 2 6

1、将整个数组置换（a[i]<=>a[n-1-i]）

2、将前k个数置换

3、将后n-k个数置换

#include<iostream>

using namespace std;

//交换a[i]与a[n-i-1]
void swapa(int* a,int n)
{
for (int i = 0; i <= (n - 1) / 2; i++)
{
int temp;
temp = a[i];
a[i] = a[n-1-i];
a[n - 1 - i] = temp;
}

}

//数组的前k个数置换a[i]与a[k-1-i]
void swappre_k(int* a,int k)
{
for (int i = 0; i <= (k - 1) / 2; i++)
{
int temp;
temp = a[i];
a[i] = a[k-1-i];
a[k - 1 - i] = temp;
}
}

void swapafter_k(int* a,int n, int k)
{
int m = n - 1;
for (int i = k; i <= ( n- 1 + k) / 2; i++)
{
int temp;
//int m = n - 1;
temp = a[i];
a[i] = a[m];
a[m] = temp;
m--;
}
}

int main()
{
int a[100], n, k;
scanf_s("%d",&n);
for (int i = 0; i < n; i++)
{
scanf_s("%d",&a[i]);
}
scanf_s("%d",&k);
cout << " 移动前数组元素: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << ' ';
}
cout << endl;
//首先是整个数组置换
int* p = a;
swapa(p,n);
//然后是前k个数置换
swappre_k(p,k);
//最后是后n-k个数置换
swapafter_k(p,n,k);
cout << " 移动后数组元素: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << ' ';
}

getchar();
return 0;
}

#include<iostream>

using namespace std;

void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void swap_reserve(int* a, int* b)
{
while (a < b)
swap(a++,b--);
}

void shift(int* a, int n, int k)
{
swap_reserve(a,a+n-1);
swap_reserve(a,a+k-1);
swap_reserve(a + k, a + n - 1);
}

//数组的前k个数置换a[i]与a[k-1-i]

int main()
{
int a[100], n, k;
scanf_s("%d",&n);
for (int i = 0; i < n; i++)
{
scanf_s("%d",&a[i]);
}
scanf_s("%d",&k);
cout << " 移动前数组元素: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << ' ';
}
cout << endl;

int* p = a;
shift(p,n,k);
cout << " 移动后数组元素: " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << ' ';
}

getchar();
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120