In C language Not c++ or java Consider the following struct definition: struct s
ID: 3855466 • Letter: I
Question
In C language Not c++ or java
Consider the following struct definition: struct song { char title(100);/* a string less than 100 characters long */ char album [100]: char artist(100]: int year;/* any integer value */ int playlist: }: Implement a sorting algorithm that accepts a special key as input that identifies which kind of sort to perform: 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 song Item: void sort (Item a[], int size, int. key);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;
}
}
}