题目:
编写一个C语言程序,该程序需实现以下功能:
- 定义一个结构体
Person
,包含姓名(char
数组)、年龄(int
)和性别(char
)三个成员。 - 定义一个函数
void sortPersonsByAge(Person* persons, int num)
,该函数接收一个Person
类型的指针数组和数组的长度,按照年龄对数组中的Person
进行升序排序。排序算法需使用归并排序(Merge Sort)。 - 在主函数中,创建一个包含至少10个
Person
的数组,并初始化这些Person
的姓名、年龄和性别。 - 调用
sortPersonsByAge
函数对数组进行排序。 - 打印排序后的数组。
解答过程:
首先,我们需要定义Person
结构体:
c复制代码
#include <stdio.h> | |
#include <string.h> | |
typedef struct { | |
char name[50]; | |
int age; | |
char gender; | |
} Person; |
接着,我们来实现归并排序的递归函数merge
和mergeSort
。注意,这里的mergeSort
是归并排序的入口函数,而merge
是合并两个有序数组的函数。
c复制代码
void merge(Person arr[], int left, int mid, int right) { | |
Person temp[right - left + 1]; | |
int i = left, j = mid + 1, k = 0; | |
// Merge the temp arrays | |
while (i <= mid && j <= right) { | |
if (arr[i].age <= arr[j].age) { | |
temp[k++] = arr[i++]; | |
} else { | |
temp[k++] = arr[j++]; | |
} | |
} | |
// Copy remaining elements of left subarray, if any | |
while (i <= mid) { | |
temp[k++] = arr[i++]; | |
} | |
// Copy remaining elements of right subarray, if any | |
while (j <= right) { | |
temp[k++] = arr[j++]; | |
} | |
// Copy temp[] back to arr[l..r] | |
for (i = left, k = 0; i <= right; ) { | |
arr[i++] = temp[k++]; | |
} | |
} | |
void mergeSort(Person arr[], int left, int right) { | |
if (left < right) { | |
// Find the middle point | |
int mid = left + (right - left) / 2; | |
// Sort first and second halves | |
mergeSort(arr, left, mid); | |
mergeSort(arr, mid + 1, right); | |
merge(arr, left, mid, right); | |
} | |
} |
现在,我们可以定义sortPersonsByAge
函数,它实际上就是调用mergeSort
函数的包装函数:
c复制代码
void sortPersonsByAge(Person* persons, int num) { | |
mergeSort(persons, 0, num - 1); | |
} |
最后,我们在主函数中创建Person
数组,初始化它们,调用排序函数,并打印结果:
c复制代码
int main() { | |
Person persons[] = { | |
{"Alice", 25, 'F'}, | |
{"Bob", 20, 'M'}, | |
{"Charlie", 30, 'M'}, | |
{"David", 22, 'M'}, | |
{"Eve", 28, 'F'}, | |
{"Frank", 27, 'M'}, | |
{"Grace", 21, 'F'}, | |
{"Henry", 29, 'M'}, | |
{"Isabella", 23, 'F'}, | |
{"Jack", 24, 'M'} | |
}; | |
int num = sizeof(persons) / sizeof(Person); | |
sortPersonsByAge(persons, num); | |
// Print sorted array | |
for (int i = 0; i < num; i++) { | |
printf("Name: %s, Age: %d, Gender: %c\n", persons[i].name, persons[i].age, persons[i].gender); | |
} | |
return 0; | |
} |
这个程序使用了归并排序算法,归并排序是一个分治策略的排序算法,它将一个数组分成两个较小的子数组,分别进行排序,然后将两个已排序的子数组合并成一个最终的已排序数组。