I have been trying to figure out what is wrong with the code below. I have taken concepts from a bubble sort tutorial on youtube. My code appears to be the same however when I print the output, the sort is incorrect. Any help is greatly appreciated. Thank you.
void onlineAddressBookType::sortContactByLastName()
{
// Order the contact list by last name
extPersonType tmpPersonObject;
int end = index; // end for inner loop
int length = index;
for(int counter = length - 1; counter > 0; counter--) //outer loop
{
for(int i = 0; i < end; i++) // inner loop
{
if(myAddresses[i].getLastName() > myAddresses[i + 1].getLastName()) // compare first two address objects found
//if the string comparison evaluates to true do this!
{
tmpPersonObject = myAddresses[i + 1]; // hold this address object for future placement
myAddresses[i + 1] = myAddresses[i]; //move this address object over one position to the right
myAddresses[i] = tmpPersonObject; // take the temporary address object and move it the lower position
} //end if
} // end inner for
end--;
} //end outer for
for(int i = 0; i < index; i++) // loop through the new arranged array and print
{
myAddresses[i].print();
}
}//ii
I have modded the code above to use this bubble sort code. It makes it easier to follow as there is no reverse counting loop. BTW my problem was with a <CRLF> returning as a address record. I have since removed the offending line and the sort works as expected. Thanks for reading!
void onlineAddressBookType::sortContactByLastName()
{
// Order the contact list by last name
extPersonType tmpPersonObject; // temp object holder
int i, j, flag = 1; // set flag to 1 to start first pass
int numLength = index;
for(i = 1; (i <= numLength) && flag; i++)
{
flag = 0;
for (j=0; j < (numLength -1); j++)
{
if(myAddresses[j+1].getLastName() < myAddresses[j].getLastName()) //compare first two address objects found
//if the string comparison evaluates to true do this!
{
tmpPersonObject = myAddresses[j]; // swap elements
myAddresses[j] = myAddresses[j+1];
myAddresses[j+1] = tmpPersonObject;
flag = 1; // indicates that a swap occurred.
}
}
}
for(int i = 0; i < index; i++) // loop through the new arranged array and print
{
myAddresses[i].print();
}
}