# qsort() bug?



## uair (Mar 28, 2012)

Hi,

*F*irst of all, some relevant info:


```
$ uname -a
FreeBSD myhost 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan  3 07:46:30 UTC 2012     
root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC  amd64
```

and


```
$ gcc --version
gcc (GCC) 4.2.1 20070831 patched [FreeBSD]
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
```

When I compile the following C program:


```
# include <stdio.h>
# include <stdlib.h>
# include <math.h>

# define N 10

int
cmp(const void *p1, const void *p2)
{
	return *(float *)p1 < *(float *)p2;
}

int
main(void)
{
	float *p, *v;

	v = malloc(N*sizeof(float));
	for(p = v; p < v+N; p++)
		*p = sin((long)p);
	for(p = v; p < v+N; p++)
		printf("%g\n", *p);
	printf("sorted\n");
	qsort(v, N, sizeof(float), cmp);
	for(p = v; p < v+N; p++)
		printf("%g\n", *p);
	return 0;
}
```

and then execute it, I get the following output:


```
-0.335083
-0.494026
0.980917
-0.788314
0.049636
0.723425
-0.995361
0.577797
0.240014
-0.891564
sorted
-0.891564
-0.494026
0.980917
-0.788314
0.049636
0.723425
-0.335083
0.577797
0.240014
-0.995361
```

*A*m I making a very stupid mistake, or perhaps qsort() simply doesn't work? (in case it's just a stupid mistake, sorry for the noise).
Saludos.


----------



## fonz (Mar 28, 2012)

uair said:
			
		

> ```
> int
> cmp(const void *p1, const void *p2)
> {
> ...


The problem is in your comparison function. It's supposed to return:
-1 when p1<p2 (omitting the casts and pointer dereferences for clarity)
0 when p1==p2
1 when p1>p2
But your function returns:
1 when p1<p2
0 when p1>=p2
-1 never
I assume that, knowing what's wrong, you can fix it yourself but feel free to ask if you encounter any other problems.

Fonz


----------



## uair (Mar 28, 2012)

You are right. I made a stupid mistake. Thanks a lot.


----------

