c - 如何使用 mergesort 对具有相同姓氏的名称进行排序?
问题描述
我们的老师给了我们一个 csv 文件,我们应该根据他们的姓氏按字母顺序对名字进行排序。但是有些名字的姓氏相同,我的代码只适用于他们的姓氏。当他们有相同的姓氏时,我不知道要添加什么来按他们的名字对他们进行排序。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define people 11
struct list_people {
char FirstName[20];
char LastName[20];
char Name[20];
char Age[5];
};
typedef struct list_people Details;
int merge_sort();
int merge(Details *[11], int, int, int);
int main() {
FILE *info;
int i, j;
Details A[people];
Details *cell[people];
for (i = 0; i < (people + 1); i++) {
cell[i] = &A[i];
}
info = fopen("people.csv", "r");
for (i = 0; i < people; i++) {
fscanf(info," %[^,], %[^,], %8s", A[i].LastName, A[i].FirstName, A[i].Age);
}
fclose(info);
merge_sort(cell, 1, people - 1);
for (i = 1; i < people; i ++) {
printf( "\t %-20s %-20s Age:%-20s \n", A[i].FirstName, A[i].LastName, A[i].Age);
}
}
int merge_sort(Details *A[], int low, int high) {
int mid;
if (low < high) {
mid = (low + high) / 2;
merge_sort(A, low, mid);
merge_sort(A, mid + 1, high);
merge(A, low, mid, high);
}
return 0;
}
int merge(Details *A[], int low, int mid, int high) {
int leftIndex = low;
int rightIndex = mid + 1;
int combinedIndex = low;
int i, j;
Details tempA[people];
while (leftIndex <= mid && rightIndex <= high) {
if (strcasecmp((A[leftIndex]->LastName), (A[rightIndex]->LastName)) <= 0) {
tempA[combinedIndex] = *(*(A + leftIndex));
combinedIndex++;
leftIndex++;
} else {
tempA[combinedIndex] = *(*(A + rightIndex));
combinedIndex++;
rightIndex++;
}
}
if (leftIndex == mid + 1) {
while (rightIndex <= high) {
tempA[combinedIndex] = *(*(A + rightIndex));
combinedIndex++;
rightIndex++;
}
} else {
while (leftIndex <= mid) {
tempA[combinedIndex] = *(*(A + leftIndex));
combinedIndex++;
leftIndex++;
}
}
for (i = low; i <= high; i++) {
*(*(A + i)) = tempA[i];
}
return 0;
}
解决方案
您可以使用以下方式比较元素:
int cmp;
// compare the last names
cmp = strcasecmp( ( A[leftIndex]->LastName), ( A[rightIndex]->LastName) );
if (cmp == 0)
{
// last names are identical so compare the first names
cmp = strcasecmp( ( A[leftIndex]->FirstName), ( A[rightIndex]->FirstName) );
}
if (cmp <= 0)
{
// ...
}
else
{
// ...
}
推荐阅读
- python - 一组线的Python凹壳多边形
- spatial - 您可以使用带有 NetTopologySuite 的实体框架 2.2 执行 Geometry 数据类型的 Sql Bulk Insert 吗?
- c++ - 如何将函数作为 cuda 内核参数传递?
- python - Pygame for-loop 只运行一次
- php - 如何处理 webonyx/graphql-php 中的自定义错误?
- azure - 使用邮递员对 Azure 存储模拟器进行授权?
- asp.net - 配置 Visual Studio 或 Chrome 以在同一个新浏览器窗口中启动多个 Asp.Net 项目
- docker - Docker 使用 ansible 'Docker login' 和 _json_key 登录到 GCE
- javascript - 使用 Keycloak 和 React 路由器在单个 Web 应用程序上同时拥有公共和私有路由的最佳方法是什么?
- php - 没有重定向的wordpress动态网址