问题
The following is my code:
#include <stdlib.h>
#include <stdio.h>
#include <limits>
#define INFINITY std::numeric_limits<float>::infinity()
#define NEGINFINITY -std::numeric_limits<float>::infinity()
int floatcomp(const void* elem1, const void* elem2)
{
if (*(const float*)elem1 < *(const float*)elem2)
return -1;
return *(const float*)elem1 > *(const float*)elem2;
}
int main()
{
float array[10] = {INFINITY, 3.5f, 144.4f, NAN, 12.4f, NEGINFINITY, 1.4f, -0.0f, 5.9f};
int i;
for (i = 0; i < 10; i++)
printf("%f\n", array[i]);
printf("\n");
qsort(array, 10, sizeof(float), floatcomp);
for (i = 0; i < 10; i++)
printf("%f\n", array[i]);
return 0;
}
The quicksort algorithm sorts the numbers entered in the correct order however, there is a 0.00000 always present in the list.
Also while adding the NaN to the array, the NaN is not sorted properly as it should be and I'm not able to correctly add in two different mantissa's for the NaN into my code as a string at the top.
回答1:
To answer why there is a zero always included, that's because you are declaring an array of 10 elements, but you initialize it with only 9, so the 10th is zero.
As for the NaN, you should explain precisely what your definition of sorting a NaN "properly" is, and how the result differs from what you expected.
回答2:
Using the normal operator rules for comparing doubles, sorting a list containing Nans is technically undefined behaviour as a < b and b < a may not be consistent. So you have to detect Nan and make it either the highest or lowest value explicitly.
int myisnan(float x)
{
return (x == x) ? 0 : 1;
}
int floatcomp(const void* elem1, const void* elem2)
{
int nan1= myisnan( *(const float *) elem1);
int nan2 = myisnan( *(const float *) elem2);
if(nan1 && nan2)
return 0;
if(nan1 && !nan2)
return -1;
if(!nan1 && nan2)
return 1;
if (*(const float*)elem1 < *(const float*)elem2)
return -1;
return *(const float*)elem1 > *(const float*)elem2;
}
Use a "my" function to prevent name clashes with other isnan() functions which may or may not have been defined. nans do not equal each other, all operations with them return NaN or false.
来源:https://stackoverflow.com/questions/42721985/why-is-there-a-0-floating-point-in-my-quicksort-algorithm-list-and-how-to-includ