Given the following type definition: typedef struct { char name[100]; int score;
ID: 3553187 • Letter: G
Question
Given the following type definition: typedef struct { char name[100]; int score; } scores; Write a complete function (not an entire program) named Sort that has three parameters - two arrays of structures (the same number of elements) and an int that is the number of elements in the arrays. The function should copy the values from the the first array to the second array, putting them in order in the second array by the score field in each structure. Hint - find the smallest score structure in the first array and copy it to the first element of the second array, then find the next smallest score structure in the first array and copy it to the second element of the second array, then find the next smallest score structure in the first array and copy it to third element of the second array, etc. This will require nested loops.Explanation / Answer
Code:
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[100];
int score;
}scores;
//Function Sort
void Sort(scores first[],scores second[], int n) {
int i;
for(i=0;i<n;i++){
second[i]=first[i];
}
for(i=0;i<n;i++)
{
int j,min;
min=i;
for(j=i;j<n;j++)
{
if(second[j].score <second[min].score)
{
min=j;
}
}
scores temp;
temp=second[i];
second[i]=second[min];
second[min]=temp;
}
printf("Sorted array of structure scores ");
for(i=0;i<n;i++){
printf("name = %s ",second[i].name);
printf("score = %d ",second[i].score);
}
}
//Main program to test the function Sort
int main()
{
scores first[4];
scores second[4];
strcpy(first[0].name,"a");
first[0].score=10;
strcpy(first[1].name,"b");
first[1].score=8;
strcpy(first[2].name,"c");
first[2].score=9;
strcpy(first[3].name,"d");
first[3].score=6;
int i;
Sort(first,second,4);
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.