# sort array by names

• 10-14-2001
plivermo
sort array by names
I can sort numeric data,but dont understand how to sort string data. help please.
Phil
• 10-14-2001
Procyon
It's the same idea, except you need a routine that can determine which of two strings is closer to the start of the alphabet than the other.

Such a routine need not be very complicated: just compare corresponding characters, starting with the first character in each string. If they're different, return a value indicating which one was lesser. If they're the same, keep scanning through the string until you find a pair of characters that are different. Things only get complicated if you want to worry about spaces and so on.
• 10-14-2001
Procyon
There's also a function which does this for you, by the way, so you don't have to do it yourself. It's strcmp(), in string.h.
• 10-14-2001
The Unregistered One
Yeah just use strcmp and its pretty much the same as sorting numeric data.
Something like this should work:
for(count2=0;count2<MAX_ARRAY;count2++)
{
for(count=0;count<MAX_ARRAY;count++)
{
if(strcmp(string,string2)>0)
{
strcpy(temp,string);
strcpy(string,string2);
strcpy(string2,temp);
}
}
}
I think it'll work, but I haven't tested it so no guarantees. Hope this helps.
• 10-21-2001
rahat
Re: sort array by names
There are many ways of arranging arrays.
1) you can compare the elements of the arrays one to another
without converting them into string. I think this is much better to be done if the aim is just to arrange integers.
2) itoa() is a nice function to use if we want the elements to be
arranged using string comparing algorithm.
• 10-21-2001
pinko_liberal
if you want to sort and are too lazy to write a sort function you can try the qsort function defined in stdlib.h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct cust
{
char *name;
int id;
} custs[]=
{
{"ellery queen",1424},
{"sherlock homes",1234},
{"hercule poirot",3341}
};

int comp1(const void *s1,const void *s2)
{
return strcmp(((struct cust *)s1)->name,((struct cust *)s2)->name);
}

int comp2(const void *s1,const void *s2)
{
return ((struct cust *)s1)->id-((struct cust *)s2)->id;
}

void write(const struct cust *s,int n)
{
int i;
for(i=0;i<n;i++)
printf("name:%s\tid:%d\n",s[i].name,s[i].id);
}
int main(void)
{
printf("Original order\n");
write(custs,sizeof(custs)/sizeof(*custs));
printf("sorted by name\n");
qsort(custs,sizeof(custs)/sizeof(*custs),sizeof(*custs),comp1);
write(custs,sizeof(custs)/sizeof(*custs));
printf("sorted by id\n");
qsort(custs,sizeof(custs)/sizeof(*custs),sizeof(*custs),comp2);
write(custs,sizeof(custs)/sizeof(*custs));
return 0;
}