How to bubble sort floats?

Started by
2 comments, last by Rob Loach 19 years, 3 months ago
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]
Julio A. Cruz
Advertisement
can you atleast explain what is what here ? I can hardly understand what these variables are.
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

<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ | MVP Profile | Developer Journal ]</small>

Don't feel bad about using the STL:


#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;}
Rob Loach [Website] [Projects] [Contact]

This topic is closed to new replies.

Advertisement