sort

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
bugzpodder
Experienced poster
Posts: 147
Joined: Fri Jun 13, 2003 10:46 pm

sort

Post by bugzpodder »

how do u sort character arrays in C
Junayeed
New poster
Posts: 50
Joined: Sat Oct 26, 2002 9:02 am
Location: Dhaka, Bangladesh

Post by Junayeed »

Normally I use Bubbel Sort charecter arrays. But its not fast enough.
And for string I use built in Qsort.
Junayeed
little joey
Guru
Posts: 1080
Joined: Thu Dec 19, 2002 7:37 pm

Post 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).
Mohammad Mahmudur Rahman
Experienced poster
Posts: 154
Joined: Sat Apr 17, 2004 9:34 am
Location: EEE, BUET

Post by Mohammad Mahmudur Rahman »

I use the built-in quick sort as I think it saves considerable coding time.
You should never take more than you give in the circle of life.
Larry
Guru
Posts: 647
Joined: Wed Jun 26, 2002 10:12 pm
Location: Hong Kong and New York City
Contact:

Post 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.. =)
Larry
Guru
Posts: 647
Joined: Wed Jun 26, 2002 10:12 pm
Location: Hong Kong and New York City
Contact:

Post 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.. =)
sumankar
A great helper
Posts: 286
Joined: Tue Mar 25, 2003 8:36 am
Location: calcutta
Contact:

Post 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.
Last edited by sumankar on Fri Dec 17, 2004 6:08 am, edited 1 time in total.
Larry
Guru
Posts: 647
Joined: Wed Jun 26, 2002 10:12 pm
Location: Hong Kong and New York City
Contact:

Post 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]
sumankar
A great helper
Posts: 286
Joined: Tue Mar 25, 2003 8:36 am
Location: calcutta
Contact:

Post by sumankar »

You are right Larry, I was in a hurry and it was a typo.I didnt mean to compare structs !!!!

Thanks!
Post Reply

Return to “C”