已知在一维数组A[m+n]中依次存放两个线性表(a1,a2,a3,...,am)和(b1,b2,b3,...,bn).编写一个函数,将数组中两个顺序表的位置互换,即将(b1,b2,b3,...,bn)放在(a1,a2,a3,...,am)的前面
算法思想:先将数组A[m+n]中的全部元素(a1,a2,a3...,am,b1,b2,b3,...,bn)原地逆置为(bn,bn-1,bn-2,...,b1,am,am-1,am-2,...,a1),再对前n个元素和后面m个元素分别使用逆置算法,即可得到(b1,b2,b3,...,bn,a1,a2,a3,...,am),从而实现顺序表的位置互换
bool Reverse(int *A, int left, int right, int arraySize)//逆置
{
if(left >= right || right >= arraySize)
return false;
int mid = (left+right)/2;
for(int i = 0; i <= mid-left; ++i)
{
int temp = A[left+i];
A[left+i] = A[right-i];
A[right-i] = temp;
}
}
void Exchange(int *A,int m, int n, int arraySize)//元素互换
{
Reverse(A,0,m+n-1,arraySize);
Reverse(A,0,n-1,arraySize);
Reverse(A,n,m+n-1,arraySize);
}
结果:
完整代码:
#include<stdio.h>
#include<stdlib.h>
//函数说明
bool Reverse(int *A, int left, int right, int arraySize);
void Exchange(int *A,int m, int n, int arraySize);
void PrintList(int *A,int m,int n);
int main(void)
{
int A[11] = {1,2,3,4,5,6,7,8,9,10,11};
int m,n;
printf("请输入m和n的值:\n");
scanf("%d%d",&m,&n);
if(m+n != 11)
{
printf("输出错误,结束运行!\n");
exit(-1);
}
Exchange(A,m,n,11);
PrintList(A,m,n);
return 0;
}
bool Reverse(int *A, int left, int right, int arraySize)
{
if(left >= right || right >= arraySize)
return false;
int mid = (left+right)/2;
for(int i = 0; i <= mid-left; ++i)
{
int temp = A[left+i];
A[left+i] = A[right-i];
A[right-i] = temp;
}
}
void Exchange(int *A,int m, int n, int arraySize)
{
Reverse(A,0,m+n-1,arraySize);
Reverse(A,0,n-1,arraySize);
Reverse(A,n,m+n-1,arraySize);
}
void PrintList(int *A,int m,int n)
{
int i;
for(i = 0; i<m+n; ++i)
{
printf("%d\n",A[i]);
}
return;
}