子数组换位问题 C语言
作者:互联网
#include <stdio.h>
//设a[0:n-1]是一个有n个元素的数组,k(0<=k<=n-1)是一个非负整数。
//试设计一个算法将子数组a[0:k-1]与a[k,n-1]换位。要求算法在最坏情况下耗时O(n),且只用到O(1)的辅助空间。
void swap(int a[],int low1, int high1, int low2) {
int temp;
while(low1 <= high1) {
temp = a[low1];
a[low1] = a[low2];
a[low2] = temp;
low1++;
low2++;
}
}
void pation(int a[],int low, int high, int k) {
if(low < high) {
if((k-low) == (high-k+1)) {//等长直接交换
swap(a,low,k-1,k);
}else if((k-low) > (high-k+1)) {//前段大于后段,将前段与后段等长交换
swap(a,low,low+high-k,k);
pation(a,low+high-k+1,high,k);
}else{//后段大于前段,将后段与前段等长交换
swap(a,low,k-1,high+low-k+1);
pation(a,low,high+low-k,k);
}
}
return;
}
int main() {
int n;
scanf("%d",&n);
int a[n],k;
for(int i = 0;i < n; i++) {
scanf("%d",&a[i]);
}
scanf("%d",&k);
pation(a,0,n-1,k);
for(int j = 0; j < n; j++) {
printf("%d ",a[j]);
}
}
标签:前段,int,换位,scanf,C语言,high,low,数组,pation 来源: https://blog.csdn.net/qq_41841130/article/details/94049057