实现奇偶数的重排问题C语言代码
时间: 2023-06-01 07:04:36 浏览: 61
以下是奇偶数重排问题的C语言代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void paritySort(int arr[], int n) {
int i = 0, j = n - 1;
while (i < j) {
while (arr[i] % 2 == 1 && i < j) {
i++;
}
while (arr[j] % 2 == 0 && i < j) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
}
}
int main() {
int arr[MAX_SIZE], n;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
paritySort(arr, n);
printf("The sorted array is: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
代码实现中使用了一个 `swap` 函数,用于交换数组中两个元素的位置。`paritySort` 函数通过两个指针 `i` 和 `j` 分别从数组的左右两端开始向中间遍历,当左指针指向的元素为奇数时,向右移动左指针,当右指针指向的元素为偶数时,向左移动右指针,最后当左指针小于右指针时交换两个指针指向的元素。这样,经过一次遍历之后,奇数和偶数就被分别排到了数组的左右两端,然后我们可以递归的对左右两个子数组进行同样的排序操作,最终得到一个完整的奇偶数重排的数组。