【问题标题】:Bubble Sort function in CC中的冒泡排序函数
【发布时间】:2013-05-10 18:13:57
【问题描述】:

我正在开始 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;
}

【问题讨论】:

  • void bubblesort(int, int); 参数int,int ??你是怎么排序的?
  • 我正在对年龄进行排序,所以是 21、18、20、17、16。就像我说的,我不确定如何告诉函数接受这些参数。
  • E.g.void bubblesort(struct person[], int start_index, int end_index); 指的是 qsort 如果你是通用的。

标签: c function sorting structure bubble-sort


【解决方案1】:

如果要根据字段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);

函数原型为void bubble(struct person *);

【讨论】:

  • 谢谢。 '空泡(struct person * stud);'是我真正需要的,但看到整个循环很有帮助。
猜你喜欢
  • 1970-01-01
  • 2016-02-06
  • 2014-03-26
  • 2018-11-13
  • 2018-05-25
  • 2014-02-25
  • 1970-01-01
相关资源
最近更新 更多