Search code examples
cfunctionsortingstructurebubble-sort

Bubble Sort function in C


I'm beginning C language lessons, specifically functions. My task is to sort the structure of arrays by numerical value, in this case that value is the variable 'age.'

I'm unsure how I should prototype to take the proper arguments, and where to go from there. Some guidance would be greatly appreciated. Thanks in advance.

#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;
}

Solution

  • If you want to sort the structure data based on the field age, then you can use the following code,

    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;
         }
      }
    }
    

    In order to achieve this you can pass the structure by reference as follows,

    void bubble(struct person * stud);
    

    The prototype for the function is void bubble(struct person *);