Hey, i am trying to do a sort in C++. I have a strucutre of different records such as Quote number, Surname, Total cost and Deliverycost. I am trying to sort in order of Quote Number. Im using a bubble sort to do this:

for(i = 1; (i <= LastRefNum) && flag; i++)
{
  flag = 0;
  for (j=0; j < LastRefNum; j++)
  {
   if (Quote[j+1].RefNumber < Quote[j].RefNumber)
   {
    //Swap the records here
   }

Its the swapping thats the problem. It works for the quote number, and costs but the names won't swap. Im using this code to swap the int's places:

RefnumberTemp = Quote[j].RefNumber;
Quote[j].RefNumber = Quote[j+1].RefNumber;
Quote[j+1].RefNumber = RefnumberTemp;

And i am using this for the surname:

strcpy (SurnameTemp, Quote[j].Surname);
strcpy (Quote[j+1].Surname, Quote[j].Surname);
strcpy (SurnameTemp, Quote[j+1].Surname);

I dont think tis algorithym is working though. Any help greatful. Thanks.

Are the names defined as std::strings or char[].

If it is char[] don't forget you need to use strcmp to actually compare them.

If you are using std::string you can overload the > operator.

Are the names defined as std::strings or char[]

They are defined as char[],

So i compare them first, and then swap them? The swap doesn't seem to work though.

And why do i need to compare them before i swap them?

Thanks, Ian

RefnumberTemp = Quote[j].RefNumber;
Quote[j].RefNumber = Quote[j+1].RefNumber;
Quote[j+1].RefNumber = RefnumberTemp;

Assuming the above logic works shouldn't it the the below?

strcpy (SurnameTemp, Quote[j].Surname);
strcpy (Quote[j].Surname, Quote[j+1].Surname);
strcpy (Quote[j+1].Surname,SurnameTemp);

Since structure assignment is supported, just do

temp = Quote[j+1];
Quote[j+1] = Quote[j];
Quote[j] = temp;

where temp is the same type as the struct used for your array.

This article has been dead for over six months. Start a new discussion instead.