Reputation: 1765
#include <stdio.h>
#include <string.h>
void sort_names();
struct ListNames {
char names[20];
int age;
}n[6] = {
{"Ryan, Elizabeth",62},
{"McIntyre, Osborne",84},
{"DuMond, Kristin",18},
{"Larson, Lois",42},
{"Thorpe, Trinity",15},
{"Ruiz, Pedro",35},
};
int main (void) {
int i;
printf("Original List");
printf("\n-----------------------------");
for (i = 0; i < 6; i++) {
printf("\n%-20s",n[i].names);
printf(" %2i",n[i].age);
}
}
I am trying to sort the strings in the struct in alphabetical order, along with the int with the string. I am able to print it fine, but I am clueless on what to do next on calling the struct to sort it in alphabetical order. I know i am going to need an index value but I dont know how i would do that within a struct.
Upvotes: 0
Views: 74
Reputation: 7542
You can iterate over your entire list while keeping track of the smallest element.By smallest i mean by name.That element(name and age) is then swapped by the element at first position.Then the second smallest element is replace by element at second position in similar fashion.
int is_smaller(char *a,char *b)//returns true if a<b
{
if(strcmp(a,b)<0)
return 1;
else
return 0;
}
void swap(char* a,char* b)//to swap names
{
char arr[100];
strcpy(arr,a);
strcpy(a,b);
strcpy(b,arr);
}
void swap(int &a,int &b)//to swap age
{
int temp=a;
a=b;
b=temp;
}
int smallest;
for(int i=0;i<6;i++)
{
smallest=i;
for(int j=i+1;j<6;j++)
if(!is_smaller(n[smallest].names,n[j].names))//is smaller return true if first argument is smaller than second
{
smallest=j;
}
if(smallest!=i)
{
swap(n[i].names,n[smallest].names);
swap(n[i].age,n[smallest].age);
}
}
Upvotes: 1