[英]Bubble Sort function in C
我正在開始C語言課程,特別是函數。 我的任務是按數值對數組的結構進行排序,在這種情況下,值是變量“年齡”。
我不確定我應該如何原型化以接受適當的論證,以及從那里去哪里。 一些指導將不勝感激。 提前致謝。
#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;
}
如果您想根據使用期限對結構數據進行排序,則可以使用以下代碼,
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);
該函數的原型為void bubble(struct person *);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.