Hi,

I'm kind of embarassed to be asking this since I should be able to figure this out by now, but I'm writing a program to sort a vector of objects alphabetically by a string member variable.

Can someone help me figure out why the bubble sort below won't work? The whole thing compiles fine but outputs the data unsorted.

for(int y = 0; y < 49; y++){
for(int x = 0; x < 49; x++){
tResult= strcmp(deansList[x].lastName.c_str(), deansList[x+1].lastName.c_str());
if(tResult > 0){
swapper = deansList[x];
deansList[x] = deansList[x+1];
deansList[x+1] = swapper;
}//if
}//loop
}//outer loop

Thanks a lot.

Do you have to write your own sort algorithm? If not, then just use std::sort() which is declared in <algorithm> header file

As for your program: I think the loops are wrong. And there is no need for strcmp()

int len = deansList.size();
for(int i = 0; i < (len-1); i++)
{
   for(int j = i+1; j < len; j++)
   {
       if( deansList[i].lastName > deansList[j].lastName)
       {

       }
   }
}

@Ancient Dragon - His Bubble sort looping looks fine.

That's the bubble sort I learned many many years ago. It's a more optimized version of the algorithm NervousWreck posted because it does not require as many comparisons. There are several bubble sort algorithms -- here is another.

k, thanks for that AD. I didn't knew of this optimized version.

But NervousWreck code also looks fine to me .. don't know what's wrong in it logically.

Ok, I wrote a test program of my own using his bubble sort algorithm that he posted, and it worked ok. So there must be something else in his program that is incorrect. The problem might be that he passed the vector by value instead of by reference to that bubble sort function.

@Nervous: You will have to post the rest of the program before we can answer your question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.