Keep in mind that this example is illustrative and uses a simplistic sorting algorithm for demonstration. For large datasets or performance-critical applications, you might want to use more efficient algorithms like quicksort or mergesort.
#include <stdio.h>
#include <string.h>
#define MAX_PEOPLE 5
// Define a structure to represent a Person
typedef struct {
char name[50];
int age;
} Person;
// Function prototypes
void printPeople(const Person people[], int size);
void sortPeopleByAge(Person people[], int size);
int main()
{
// Array of people
Person people[MAX_PEOPLE] = {
{"Alice", 30},
{"Bob", 24},
{"Charlie", 28},
{"Diana", 22},
{"Evan", 26}
};
printf("Original array:\n");
printPeople(people, MAX_PEOPLE);
// Sort the array by age
sortPeopleByAge(people, MAX_PEOPLE);
printf("\nSorted array by age:\n");
printPeople(people, MAX_PEOPLE);
return 0;
}
// Print the array of people
void printPeople(const Person people[], int size)
{
for (int i = 0; i < size; ++i) {
printf("%s, %d\n", people[i].name, people[i].age);
}
}
// Sorts an array of people based on their age using bubble sort
void sortPeopleByAge(Person people[], int size)
{
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (people[j].age > people[j + 1].age) {
// Swap the Person elements
Person temp = people[j];
people[j] = people[j + 1];
people[j + 1] = temp;
}
}
}
}
This program defines a Person structure, an array of Person named people, and two functions. The printPeople function is used for displaying the list of people, showing each person's name and age. The sortPeopleByAge function uses the bubble sort algorithm to sort the array of people based on their ages in ascending order.
Note: The sorting algorithm used here (bubble sort) is chosen for its simplicity and ease of understanding. However, bubble sort is not efficient for sorting large arrays. In practical applications, it's recommended to use more efficient sorting algorithms or functions like qsort provided by the C Standard Library.