Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following struct definition: struct student { char firstname[100];

ID: 3712363 • Letter: C

Question

Consider the following struct definition:

struct student {

  char firstname[100]; /* a string less than 100 characters long */

  char middle;

  char lastname[100];

  double gpa; /* grade point average */

  int credit_hours;/* positive numbers only */

};

Implement a sorting algorithm that accepts a special key as input that identifies which kind of sort to perform:

Key Value

Kind of Sort

0

Alphabetical order (a-z) by lastname, if lastnames are equal then by firstname (a-z). If firstnames are equal, then by middle initial. You may use strcmp to perform the ordering.

1

By gpa, largest to smallest; if equal, then by credit hours taken.

2

By credit hours, smallest to largest

Otherwise

The list remains the same

You may not implement 3 different sorting algorithms. You must implement one sorting algorithm that chooses a comparison operation based upon the value of the key variable. Use the following prototype:

typedef struct student Item;

void sort(Item a[], int size, int key);

Hint: Implement an additional function to perform the LESS operation, and pass it two pointers to each struct player you’re comparing and the key value.

the answer should be what is boxed and it should be implemented with an array of struct

Key Value

Kind of Sort

0

Alphabetical order (a-z) by lastname, if lastnames are equal then by firstname (a-z). If firstnames are equal, then by middle initial. You may use strcmp to perform the ordering.

1

By gpa, largest to smallest; if equal, then by credit hours taken.

2

By credit hours, smallest to largest

Otherwise

The list remains the same

Explanation / Answer

Below is the code snippet to do the sorting based on a key using a is_less() function.

#include <stdio.h>

#include <string.h>

struct song{

char title[100];

char album[100];

char artist[100];

int year;

int playlist;

};

typedef struct song Item;

int is_less(Item *a, Item *b, int key)

{

if(key == 0)

{

if(strcmp(a->artist, b->artist) < 0)

return 1;

else

return 0;

}

else if(key == 1)

{

if(strcmp(a->album, b->album) < 0)

return 1;

else

return 0;

}

else if(key == 2)

{

if(a->year < b->year)

return 1;

else

return 0;

}

  

return 0;

}

void sort(Item a[], int size, int key)

{

int minIdx;

int i, j;

  

//selection sort

for(i = 0; i < size; i++)

{

minIdx = i;

for( j = i+1; j < size; j++)

{

if(is_less(&a[j], &a[minIdx], key))

minIdx = j;

}

if(minIdx != i)

{

Item temp = a[i];

a[i] = a[minIdx];

a[minIdx] = temp;

}

}

}