生成一段C语言代码,要求如下:输入十个整数,将十个整数按升序排列输出,并且奇数在前,偶数在后。 输入: 输入十个整数 输出: 按照奇偶排序好的十个整数
时间: 2024-10-23 07:14:29 浏览: 23
给定N个正整数,请统计奇数和偶数各有多少个-C语言代码
以下是一段C语言代码,满足上述要求。这段代码首先读取10个整数,然后根据奇偶性进行排序,最后打印结果:
```c
#include <stdio.h>
// Function to swap two integers
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to check if a number is odd
int is_odd(int num) {
return num % 2 != 0;
}
// Bubble sort function that sorts the array based on parity
void parity_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
// If both numbers are odd or even, no swapping needed
if (is_odd(arr[j]) && is_odd(arr[j + 1])) continue;
// Swap elements if one is odd and other is even
if ((is_odd(arr[j]) && !is_odd(arr[j + 1])) || (!is_odd(arr[j]) && is_odd(arr[j + 1]))) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
int main() {
int arr[10];
printf("Enter 10 integers: ");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
parity_sort(arr, 10);
printf("Sorted array with odd numbers first followed by even numbers:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
阅读全文