473,659 Members | 2,609 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Qsort inaccuracy?

Hi All:

The code below (using the qsort function) produces the following
incorrect result. The last two numbers are not sorted. It this
innaccurate result specific to my compiler's qsort, or is there a bug
in my code? Thanks...

Original Array:
3.125420
8.618710
4.220840
2.181950
8.852060
1.763020
0.164010

Sorted Array:
0.164010
1.763020
2.181950
3.125420
4.220840
8.852060
8.618710

------------------------------------------

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

typedef int (*qsortfunc) ( const void*, const void* );
int
compare_doubles (const double *a, const double *b)
{
return (int) (*a - *b);
}

int main ()
{

int i;
double array[7];
array[0] = 3.12542;
array[1] = 8.61871;
array[2] = 4.22084;
array[3] = 2.18195;
array[4] = 8.85206;
array[5] = 1.76302;
array[6] = 0.16401;

printf ("\nOriginal Array:\n");

for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);

qsort(array, 7, sizeof(double), (qsortfunc) compare_doubles );

printf ("\nSorted Array:\n");
for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);
return 1;
}

Nov 14 '05 #1
3 2298
On Tue, 14 Dec 2004 08:04:10 -0800, No Such Luck wrote:
Hi All:

The code below (using the qsort function) produces the following
incorrect result. The last two numbers are not sorted. It this
innaccurate result specific to my compiler's qsort, or is there a bug
in my code? Thanks...

Original Array:
3.125420
8.618710
4.220840
2.181950
8.852060
1.763020
0.164010

Sorted Array:
0.164010
1.763020
2.181950
3.125420
4.220840
8.852060
8.618710

------------------------------------------

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

typedef int (*qsortfunc) ( const void*, const void* );
Get rid of that, you don't need it.
int
compare_doubles (const double *a, const double *b)
A qsort() comparison fuction is required to have 2 parameters of type
const void *. The function you have defined here is not compatible with
this and is invalid. The fact that you had to use a cast in the call to
qsort() below should ring alarm bells. Consider that qsort() will be
passing const void * arguments to the comparison function but
const double * may not have the same representation.
{
return (int) (*a - *b);
This is not valid. For example (int)(8.85206-8.61871) will evaluate to
zero but the numbers are not equal. Also consider what happens if the
difference is too big to fit in an int.
}
You need something like

int compare_doubles (const void *a, const void *b)
{
double da = *(const double *)a;
double db = *(const double *)b;

if (da == db)
return 0;

return (da > db) ? 1 : -1;
}

int main ()
{

int i;
double array[7];
array[0] = 3.12542;
array[1] = 8.61871;
array[2] = 4.22084;
array[3] = 2.18195;
array[4] = 8.85206;
array[5] = 1.76302;
array[6] = 0.16401;

printf ("\nOriginal Array:\n");

for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);
The normal printf() conversion specifier for double is %f, C99 added
support for %lf too, but %f also works with C90 which is still in common
use.

qsort(array, 7, sizeof(double), (qsortfunc) compare_doubles );
qsort(array, 7, sizeof *array, compare_doubles );

You don't need the cast, and this form of the 3rd argument works even if
you changed the type of array.
printf ("\nSorted Array:\n");
for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);
Again %f is better.

return 1;
}


Portable return values from the initial invocation of main() are 0 and
EXIT_SUCCESS which indicate success and EXUT_FAILURE which indicates
failure. The last 2 are defined in <stdlib.h>.

Lawrence
Nov 14 '05 #2
On Tue, 14 Dec 2004 16:57:46 +0000, Lawrence Kirby wrote:

....
Portable return values from the initial invocation of main() are 0 and
EXIT_SUCCESS which indicate success and EXUT_FAILURE which indicates
failure. The last 2 are defined in <stdlib.h>.


Sorry, make that EXIT_FAILURE

Lawrence

Nov 14 '05 #3


No Such Luck wrote:
Hi All:

The code below (using the qsort function) produces the following
incorrect result. The last two numbers are not sorted. It this
innaccurate result specific to my compiler's qsort, or is there a bug
in my code?
Yes.
The compare function is flawed. See below.
Original Array:
3.125420
8.618710
4.220840
2.181950
8.852060
1.763020
0.164010

Sorted Array:
0.164010
1.763020
2.181950
3.125420
4.220840
8.852060
8.618710

------------------------------------------

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

typedef int (*qsortfunc) ( const void*, const void* );
int
compare_doubles (const double *a, const double *b)
{
return (int) (*a - *b);
}
1. The return statement is wrong. For example, with
(int)(8.852060 - 8.618710), the cast to int results in a
return of 0. 0 indicates to function qsort that the two
values are equal. As you see, they are not equal.

2. The prototype for the comparison function is:
int cmp(const void *, const void *);

You need to remove the typedef.
Change the compare_doubles function to something like:

int compare_doubles (const void *v1, const void *v2)
{
const double *d1 = v1;
const double *d2 = v2;

return (*d1 < *d2)?-1:(*d1!=*d2);
}

And remove the qsortfunc cast in the qsort statement.
int main ()
{

int i;
double array[7];
array[0] = 3.12542;
array[1] = 8.61871;
array[2] = 4.22084;
array[3] = 2.18195;
array[4] = 8.85206;
array[5] = 1.76302;
array[6] = 0.16401;

printf ("\nOriginal Array:\n");

for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);

qsort(array, 7, sizeof(double), (qsortfunc) compare_doubles );

printf ("\nSorted Array:\n");
for (i = 0; i < 7; i++)
printf ("%lf\n", array[i]);
return 1;
}


--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
4653
by: richard | last post by:
What might cause qsort to crash? I'm using qsort to sort a few thousand items of a not too complex structure. Tried it with one data set - worked fine. Tried another similarly sized data set and the program dies in the midst of the qsort. My comparison function doesn't do anything fancy - just some strnicmp's and =='s.
11
2848
by: William Buch | last post by:
I have a strange problem. The code isn't written by me, but uses the qsort function in stdlib. ALWAYS, the fourth time through, the memory location of variable list (i.e. mem location = 41813698) becomes 11, then the program crashes. It is obviously qsort that may me overwritten the used memory location. The weird thing is that it is ALWAYS the fourth time running the program. Below is the code MEMORY LOCATION OK HERE for (i = 0; i...
5
3860
by: Steve | last post by:
can someone tell me how qsort function in <stdlib.h> is used (qsort(..........))? the function has a buffer, two void * parameters and the a pointer to a compare function. Thanks.
7
7452
by: Excluded_Middle | last post by:
Suppose I have a struct typdef struct foo { int age; char *name; }foo; now I made a list of foo using
17
2657
by: Trent Buck | last post by:
The fourth argument is a comparator that returns `an integer less than, equal to, or greater than zero' depending on the ordering of its arguments. If I don't care about the order and simply want qsort() to run as quickly as possible, how should the comparator be defined? If qsort were stable, the following would be best: int
32
4534
by: John Smith | last post by:
I'm trying to figure out qsort(). I haven't seen any practical examples, only synopsis. In the code below, the array is not sorted. Can someone give me some help? #include <stdio.h> #include <stdlib.h> int compare(const void* a, const void* b); int main(void) {
10
355
by: No Such Luck | last post by:
Hi All: The code below (using the qsort function) produces the following incorrect result. The last two numbers are not sorted. It this innaccurate result specific to my compiler's qsort, or is there a bug in my code? Thanks... Original Array: 3.125420 8.618710
10
2234
by: gauss010 | last post by:
Suppose I have an object A of type char. Each A is a buffer containing a string, and I want to sort the M strings of A using the strcmp function. The description of the qsort function says that I must pass a pointer to the first object of the array to be sorted. This leads me to write the following: char A; int cmp(const void *a, const void *b) { int v = strcmp(*(char (*))a, *(char (*))b); if (v < 0) return -1;
61
5820
by: Ron Ford | last post by:
K&R has three different versions of qsort, and the ultimate one is supposed to be like the one in the std library. I'm trying to implement the first, which is in §4.10. I think I'm pretty close with this: void qsort(int v, int left, int right) { int i, last;
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8539
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4176
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2759
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.