gpt4 book ai didi

c - C 中的冒泡排序函数

转载 作者:行者123 更新时间:2023-11-30 17:51:41 26 4
gpt4 key购买 nike

我正在开始 C 语言类(class),特别是函数。我的任务是按数值对数组结构进行排序,在本例中该值是变量“age”。

我不确定应该如何构建原型(prototype)以获取正确的参数,以及从哪里开始。一些指导将不胜感激。提前致谢。

#include <stdio.h>
#include <stdlib.h>

#define STUDENTS 5 //Maximum number of students to be saved.
#define LENGTH 20 //Maximum length of names.

struct person { //Setting up template for 'person'
char first[LENGTH];
char last[LENGTH];
int age;
};

void bubblesort(int, int); //Prototyping function for sorting structures.

int main(void) {

struct person student[STUDENTS] = { //Array of person structures.
{"Person", "One", 21},
{"Person", "Two", 18},
{"Person", "Three",20},
{"Person", "Four", 17},
{"Person", "Five", 16}
};

int i; //For loop counter.
int n=5; //For loop variable. N is equal to the # of entries in the struct.

printf("Here is an unsorted list of students: \n");
for( i=0; i<n; i++) {
printf("%s %s is %d years old. \n", student[i].first, student[i].last, student[i].age);
}

//Sort students by age.
//Print sorted list.

return 0;
}

最佳答案

如果你想根据字段age对结构数据进行排序,那么你可以使用下面的代码,

struct person temp;

for(i=0; i<STUDENTS; i++)
{
for(j=i; j<STUDENTS; j++)
{
if(stud[i].age < stud[j].age)
{
temp = stud[i];
stud[i] = stud[j];
stud[j] = temp;
}
}
}

为了实现此目的,您可以按如下方式通过引用传递结构,

void bubble(struct person * stud);

该函数的原型(prototype)是void bubble(struct person *);

关于c - C 中的冒泡排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com