void adjust(int *arr,int left,int right)
{
int temp;
while(left<right)
{
if(1==left%2)
left++;
if(0==right%2)
right--;
temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right--;
}
}
int main()
{
int i=0;
int a[]={1,2,3,4,5,6,7,8,9};
adjust(a,0,8);
for(i=0;i<9;i++)
{
printf("%d ",a[i]);
}
system("pause");
return 0;
}
但是在测试用例为1,3,5,7,2,4,6,8时,程序运行的结果会出错,原因是在交换前也必须判断left<right.
修改后的程序为:
void adjust(int *arr,int left,int right)
{
int temp;
while(left<right)
{
if(1==left%2)
left++;
if(0==right%2)
right--;
if(left<right)
{
temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
}
left++;
right--;
}
}