954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Swapping chars within an array

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.

iaaan
Newbie Poster
23 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

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.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 
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

iaaan
Newbie Poster
23 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

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);

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

And you need strcmp. Use it like follows:

http://www.cppreference.com/stdstring/strcmp.html

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

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.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Worked perfect, thanks guys.

iaaan
Newbie Poster
23 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You