首页 > 解决方案 > 如何使用 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;
}

标签: cmergesort

解决方案


您可以使用以下方式比较元素:

        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
        {
            // ...
        }

推荐阅读