按字母顺序将结构元素插入结构数组



我需要有关我感到困惑的函数的帮助。我需要遍历结构数组以找出我需要插入新元素的索引。结构数组由名字、姓氏、年级和年级组成。我需要按姓氏的字母顺序插入它们。如果有另一个相同的姓氏,我需要按名字的字母顺序插入它。我认为到目前为止我的想法是正确的,但我真的很困惑如何将新元素插入正确的索引,然后将结构数组中的所有其他元素移过来。这是我到目前为止为该函数编写的代码,

void add(char* student_firstname, char* student_lastname, char* student_grade, char* student_level, struct student* list)
{
if(count > 30){
    printf("No more room left in the array!");
}
else{
    for(int i = 0; i < count; i++){
        if(strcmp(list[i].lastName, student_lastname) == 0){
            // There is another last name in the list
            // Must sort alphabetically by first name
            // Sorts by first name then returns 0 and adds one to count
        }

    } // end for loop to determine if same last name is in array

    for(int i = 0; i < count; i++){
        if(strcmp(student_lastname, list[i].lastName) < 0){
            // Need to insert in index i - 1
            int index = i - 1;
        }
    }
}
}

count 变量是我的结构列表的大小。有人可以通过代码告诉我如何按姓氏的字母顺序插入新元素吗?将不胜感激。

编辑:另外,30是结构数组的最大大小。

编辑版本:

void add(char* student_firstname, char* student_lastname, char* student_grade, char* student_level, struct student* list)
{
if(count > 30){
    printf("No more room left in the array!");
}
else{
    int i = 0;
    while( i < count && compare_student( list[i], new_student ) > 0 ){
        i++;
        // Move everything over 1 and insert
    }
}
} 

我建议你的add函数做的第一件事是用提供的数据做一个student记录。 创建一个函数来比较两个student记录:

int compare_student( struct student *a, struct student *b )
{
    int cmp = strcmp( a->lastName, b->lastName );
    if( cmp == 0 ) cmp = strcmp( a->firstName, b->firstName );
    return cmp;
}

现在,在列表中查找要插入的位置要容易得多:

int i = 0;
while( i < count && compare_student( &list[i], &new_student ) > 0 ) i++;

一旦你有了它,你只需在icount右边的一个地方打乱所有东西,然后把新记录放进去。 将把这个练习留给你。

从数组的末尾开始,然后向后工作。 对于您检查的每个元素,如果它位于您要添加的元素之后,请将其复制到数组中的下一个较高位置。 继续前进,直到到达数组的开头或遇到属于要添加的元素之前的元素。 然后添加新元素。

最新更新