Page 1 of 1
sort
Posted: Sun Nov 21, 2004 9:35 pm
by bugzpodder
how do u sort character arrays in C
Posted: Mon Nov 22, 2004 4:28 am
by Junayeed
Normally I use Bubbel Sort charecter arrays. But its not fast enough.
And for string I use built in Qsort.
Posted: Mon Nov 22, 2004 10:26 am
by little joey
I use selection sort for short strings (because it's easy to remember and implement) and counting sort for long strings (because it's fast).
Posted: Fri Nov 26, 2004 1:54 am
by Mohammad Mahmudur Rahman
I use the built-in quick sort as I think it saves considerable coding time.
Posted: Thu Dec 16, 2004 1:00 am
by Larry
[c]int cmp( char *a, char *b ) {
if ( *a > *b ) return 1;
if ( *a < *b ) return -1;
return 0;
}
int main() {
char a[] = "Hey hey, I am Larry!";
qsort( a, strlen( a ), sizeof( char ), cmp );
}
[/c]
Hope it helps.. =)
Posted: Thu Dec 16, 2004 1:11 am
by Larry
Note that, most/some people write the compare like this:
[c]int cmp( int *a, int *b ) {
return *a - *b;
}[/c]
(as I used to, actually) but is prone to over/underflows.. so be careful.. =)
Posted: Thu Dec 16, 2004 9:06 am
by sumankar
Well to be accurate the sort function should be written as:
[c]
#include <stdlib.h>
struct m
{
int x, y;
};
int cmp( const void *l, const void *r )
{
struct m *a = (struct m *)l;
struct m *b = (struct m *)r;
if ( a->x > b-x )
return 1;
if ( b->x > a->x )
return -1;
return 0;
}
int main( void )
{
struct m A[10];
qsort(A, 10, sizeof(m), cmp);
return 0;
}
[/c]
Otherwise the compiler will complain, and your sort function might not work as expected.
Regards,
Suman.
Posted: Thu Dec 16, 2004 6:26 pm
by Larry
It compiles fine with -ANSI flag without warning, but if you understand it, it's fine.. =)
If you really want to be anal, you shouldn't use greater than and less than on the struct directly like you did anyhow.. it's might not work for everything.. =P[/c]
Posted: Fri Dec 17, 2004 6:07 am
by sumankar
You are right Larry, I was in a hurry and it was a typo.I didnt mean to compare structs !!!!
Thanks!