如题:
利用数组的左右指针,从两端往两头遍历数组,若左指针遇到偶数,右指针遇到奇数则奇偶替换,晓得左右指针不能挪动地位
#include<stdio.h>
#include<string.h>
void swap(int* left, int* right)// 办法一
{while (left < right)
{if ((*left) % 2 == 1)
{left++;}
if ((*right) % 2 == 0)
{right--;}
else
{
int temp = 0;
temp = *left;
*left = *right;
*right = temp;
}
}
}
void swap1(int* left, int* right)// 办法二
{while (left < right) {while ((*left) % 2 == 1)
{left++;}
while ((*right) % 2 == 0)
{right--;}
while (left < right)
{
int temp = 0;
temp = *left;
*left = *right;
*right = temp;
}
}
}
void print(int* arr,int len)
{
int i = 0;
for (i = 0; i < len; i++)
{printf("%3d", arr[i]);
}
}
int main()
{int arr[] = {1,6,5,2,7,8,10,4,9};
int len = sizeof(arr) / sizeof(arr[0]);
//swap(arr, arr + len - 1);
swap1(arr, arr + len - 1);
print(arr, len);
}
正文:当数组全为奇数或偶数时,应加上约束条件 left<right 避免指针越界拜访数组元素