Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>

// struct person with 2 fields


struct Student {
char* name;
int id;

};

// setting up rules for comparison


// to sort the students based on ID
int comparator(const void* p, const void* q)
{
return (((struct Student*)p)->id - ((struct Student*)q)->id);
}

int main()
{
int i = 0, n = 5;

struct Student arr[n];

// Get the students data


arr[0].id = 1;
arr[0].name = "bd";

arr[1].id = 2;
arr[1].name = "ba";

arr[2].id = 3;
arr[2].name = "bc";

arr[3].id = 4;
arr[3].name = "aaz";

arr[4].id = 5;
arr[4].name = "az";

printf("Unsorted Student Records:\n");


for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s,\n",
arr[i].id, arr[i].name);
}
// Sort the structure
// based on the specified comparator
qsort(arr, n, sizeof(struct Student), comparator);

// Print the Sorted Structure


printf("\n\nStudent Records sorted by ID:\n");
for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name);
}

return 0;
}

You might also like