101001
101001

Reputation: 111

How to sort by last name and print the new array?

So basically, I am creating a phone book with various information such as name, phone number, address, etc. It is saved using a class. I need some help sorting this array by last name and then print the new list.

I have tried various sorting methods. I don't know if the sorting method is working or if I am just printing the array without it being sorted yet. I created the string last1 and last2 because I was getting an error when just using addressBook[j] into the swap line. I also tried turning the strings to ascii values to compare.

void sortAddressBookByLastName(addressBookType addressBook[], int 
numOfAddress){

string last1, last2;

for (int i = 0; i < numOfAddress-1; i ++){
    for (int j = 0; j < numOfAddress - i - 1; j ++)
    {
        last1=addressBook[j].getLastName();
        last2=addressBook[j+1].getLastName();

        if (last1 > last2){
            swap(last1,last2);
        }
    }
}

for(int i=0; i < numOfAddress;i++){
    addressBook[i].print();
}

}

Upvotes: 0

Views: 139

Answers (1)

6502
6502

Reputation: 114569

Your code is swapping the local variables last1 and last2; it doesn't change elements of the array.

Upvotes: 1

Related Questions