#include <stdio.h>
int array[100] = {0};
//当第一段子数组长度小于第二段
int swapFromLeftToRight(int left, int middle, int end) {
int temp;
if(middle*2 == end+1) {
while(middle <= end) {
temp = array[middle];
array[middle] = array[left];
array[left] = temp;
left++;
middle++;
}
}
else{
while (left < end) {
temp = array[middle];
array[middle] = array[left];
array[left] = temp;
left++;
middle++;
if (middle > end) {
middle= end;
}
}
}
}
//当第一段子数组长度大于第二段
int swapFromRightToleft(int left, int middle, int end) {
int temp;
while (end > left) {
temp = array[middle];
array[middle] = array[end];
array[end] = temp;
end--;
middle--;
if(middle < left) {
middle = left;
}
}
}
int main(void) {
int n, middle;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
scanf("%d", &middle);
if(middle > n/2) {
swapFromRightToleft(0, middle-1, n-1);
}
else{
swapFromLeftToRight(0, middle, n-1);
}
for(int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
return 0;
}
算法习题——数组交换
最新推荐文章于 2024-03-25 17:27:44 发布