Public Group

How to bubble sort floats?

This topic is 5084 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello Everyone! I can't bubble sort floating point numbers, I think I need to use pointers:
[Source]
void bubblesort(char skaters[][15], float averages[], int count)
{

float stopt={0};
char *stop={0},*names[10]={0};
int a={0},b={0};

for(count=0;count<10;count++)
{
names[count] = &skaters[count][0];
}

for(a=0;a<10-1;a++)
{
for(b=a+1;b<10;b++)
{
if(averages[a]<averages);
{
stop=names[a];
stopt=averages[a];
names[a]=names;
averages[a]=averages;
names=stop;
averages=stopt;
}
}
}

}
[/Source]

Share on other sites
can you atleast explain what is what here ? I can hardly understand what these variables are.

Share on other sites
Syntax Error:
if(averages[a]<averages); // <<--- the ';' should not be here!   {    stop=names[a];    stopt=averages[a];    names[a]=names;    averages[a]=averages;    names=stop;    averages=stopt;   }

Your extra ";" effectively makes your if() a pointless construct (my compiler warns me of this, maybe you should double check you've enabled warnings and not ignored this one!). Because of this, the swapping done between { and } will be executed for every iteration - generally not a lot of use to you [smile].

Quote:
 I can't bubble sort floating point numbers

Something you may not be aware of is that comparing two floating point numbers is a bit of a grey area.

Normal bubble sort relies on lines like if(averages[a]<averages) which, for small floats (or very similar floats) may not give the results you expect. For better results you want to compare them to an epsilon value.

I think there are some definitions of what epsilon should be, but its been a while since I've messed about with it (the number varies for comparing large floats or comparing very small floats iirc).

For example, equality should be something like if( fabs(averages[a] - averages) < 0.000001f ). I think I saw a C-Macro that worked for LEQUAL/GEQUAL based on the signed bit in the representation, but as I said - it's been a while [smile]

hth
Jack

Share on other sites

#include <iostream>#include <algorithm>int main() {    float a[7] = {23.4F, 1.5F, 79.31F, -1.4F, 1.2F, 1.73F, 1.7F};        std::sort(a, a+7); // sort 7 elements        for (int i=0; i<7; i++) {        std::cout << a << "\n";    }    std::cin.get();    return 0;}

1. 1
2. 2
Rutin
19
3. 3
khawk
18
4. 4
A4L
13
5. 5

• 12
• 16
• 26
• 10
• 44
• Forum Statistics

• Total Topics
633767
• Total Posts
3013737
×