定义一个函数,实现输入的数组元素奇数在左、偶数在右,使用C语言编写并在Linux上执行
时间: 2024-05-04 16:19:11 浏览: 105
以下是实现输入的数组元素奇数在左、偶数在右的函数,并附带一个简单的测试代码:
```c
#include <stdio.h>
void oddEven(int arr[], int len) {
int left = 0;
int right = len - 1;
while (left < right) {
while (left < right && arr[left] % 2 != 0) {
left++;
}
while (left < right && arr[right] % 2 == 0) {
right--;
}
if (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(arr) / sizeof(int);
printf("Before sorting: ");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
oddEven(arr, len);
printf("After sorting: ");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行结果如下:
```
Before sorting: 1 2 3 4 5 6 7 8 9
After sorting: 1 9 3 7 5 6 4 8 2
```
阅读全文