Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define MAX 2
- #define COUNT_OF(x) (sizeof(x) / sizeof(0[x])) //length of arrays at compile time
- struct Person {
- char firstname[64];
- char lastname[64];
- int age;
- };
- int Person_cmp_firstname(const void* x, const void* y) {
- struct Person *ix = (struct Person *)x;
- struct Person *iy = (struct Person *)y;
- return strcmp(ix->firstname, iy->firstname);
- }
- int Person_cmp_lastname(const void* x, const void* y ) {
- struct Person *ix = (struct Person *)x;
- struct Person *iy = (struct Person *)y;
- return strcmp(ix->lastname, iy->lastname);
- }
- int Person_cmp_age(const void* x, const void* y) {
- struct Person *px = (struct Person *) x;
- struct Person *py = (struct Person *) y;
- return px->age - py->age;
- }
- int main(){;
- int choice;
- struct Person *P[10];
- printf("t***PROGRAM TO SORT PERSONS***nn");
- for(int i=0; i<3; i++){
- P[i] = (struct Person *) malloc(sizeof(struct Person));
- printf("Firstname: ");
- scanf("%s", P[i]->firstname);
- printf("Lastname: ");
- scanf("%s", P[i]->lastname);
- printf("Age: ");
- scanf("%d", &P[i]->age);
- printf("t***NEXT PERSON***nn");
- }
- do{
- printf("nt***CHOOSE HOW TO SORT***nntBy firstname: 1ntBy lastname: 2ntBy age: 3ntExit Program: 4nn");
- scanf("%d", &choice);
- switch(choice){
- case 1:
- printf("t***SORTING BY FIRSTNAME...***nn");
- qsort(P, COUNT_OF(P), sizeof(struct Person), Person_cmp_firstname);
- printf("t***DONE***nn");
- for(unsigned int i=0; i<3; i++){
- printf( "Firstname: %st| Lastname: %st| Age: %dn", P[i]->firstname, P[i]->lastname, P[i]->age );
- }
- break;
- case 2:
- printf("t***SORTING BY LASTNAME...***nn");
- qsort(P, COUNT_OF(P), sizeof(struct Person ), Person_cmp_lastname);
- printf("t***DONE***nn");
- for(unsigned int i=0; i<3; i++){
- printf( "Firstname: %st| Lastname: %st| Age: %dn", P[i]->firstname, P[i]->lastname, P[i]->age );
- }
- break;
- case 3:
- printf("t***SORTING BY AGE...***nn");
- qsort(P, COUNT_OF(P), sizeof(struct Person), Person_cmp_age);
- printf("t***DONE***nn");
- for(unsigned int i=0; i<3; i++){
- printf( "Firstname: %st| Lastname: %st| Age: %dn",P[i]->firstname, P[i]->lastname, P[i]->age );
- }
- break;
- case 4:
- printf("t***EXITING PROGRAM***nn");
- for (int j = 0; j < 3; j++) {
- free(P[j]);
- }
- exit(0);
- default:
- printf("t***INVALID OPTION***nn");
- break;
- }
- }while(1);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement