Finally, a functional bubble sort. And all I had to do was stare at someone else’s code to see what I was doing wrong.
And then stare at it some more. And some more. BLAH.
#include <iostream>
int sort[] = { 6, 3, 2, 5, 4, 1 }; // Curly braces - NOT brackets.
int i, x, y;
bool z; // didn’t work until after switching to bool NOT int
int elements;
int main() {
elements = sizeof(sort)/sizeof(sort[0]); // How many elements are we sorting?
do {
z = false; // swapper is false
for (i = 0; i < elements-1; i++) { // elements-1 was the single most important breakthrough
if (sort[i] > sort[i+1]) {
x = sort[i];
y = sort[i+1];
sort[i+1] = x;
sort[i] = y;
z = true; // Swapper is true
}
std::cout << i << x << y << ” - “;
}
} while (z); // while swapper is true
std::cout << “\n”;
for (i = 0; i < elements ; i++) { // so this should go display the sorted information
std::cout << i+1 << ” : ” << sort[i] << “\n”;
}
return 0;
}
At one point, I only had the do…while loop. Before that I had only the for loop. Of course, neither one by itself was doing what I wanted. As soon as I saw that in my reference program, I slapped myself.
The next thing that seemed to make a big difference was when I went from
x = sort[i+1];
y = sort[i];
to
x = sort[i];
y = sort[i+1];
and I really just don’t understand why that would matter. I saw the same thing in PHP when I was doing my stupid multi-dimension array for making mazes. I do not understand why, but it seems to make a big difference. Like, from it doesn’t work - to it does work.
Next up, I stopped using “z”, my swapper variable, as an integer. I was under the impression that when evaluating an expression, a variable equal to null/zero is equivalent to false and one equal to one was also true. That may very well be the case, but going over to using “z” as a boolean worked much better.
Then there was the big head slapper. No, really, the BIG head slapper. My for loop, set to the limit of “elements”? Arrays count from 0, ‘cuz its binary. Dur. Dur duh duh! So the limit should be set to “elements-1″. So that it also will start from 0. [seething angrily at self-stupidity]
But even at that point, I was getting a functional bubble sort that was stuck in an infinite loop. And the reason that it was looping? Because
} while (z = true);
and
} while (z);
have different meanings? If my boolean variable “z” is true, how does “equals true” differ from “is true”??? Well, as soon as I went to the second style … that’s when my bubble sort finally actually worked. I don’t understand.