【发布时间】:2020-10-22 14:39:08
【问题描述】:
我们的教练给了我们一个 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;
}
【问题讨论】:
-
您可以通过点击分数下方的灰色复选标记来接受答案。