0

Hello Everyone I created an address book by using arrays !... Here I got a problem with sorting arrays of type String .... When I want to Sort a contacts It will just Sort the first names Without moving Second name and phone numb..... etc .. I have no clear Idea about Moving whole line to sort in the address book ! ... I mean moving [first name, surname, phone number, Email] at the same time to the next line !... here is my Code!

void sortRecords() {

ofstream Cfile; 
Cfile.open("addressbook.txt", ios::in); 

string temp;
for (int i=0; i<line()-1; ++i)
{
    for (int j=0; j<line()-1-i; j++)
    {
        while (first_name[j]>first_name[j+1])
        {
            temp= first_name[j+1];
            first_name[j+1]=first_name[j];
            first_name[j]=temp;
        }
    }
}
for (int p=0; p<line();p++)
{

    Cfile<<first_name[p]<<setw(10)<<sur_name[p]<<setw(10)<<phone_number[p]<<setw(10)<<email[p]<<endl;
}
Cfile.close();
}
Floris
  • 45,857
  • 6
  • 70
  • 122

1 Answers1

0

The efficient way to do this is with a second (numerical) array of "indirection pointers" - which say "the item originally at i is now at j". Then you only have to swap these indices around; but when you're done, you can generate the sorted array by running down this index array just once and making a copy of the elements. This is usually a good way to do it when you are sorting "bunches of stuff".

Alternatively, you just move all the items to their new location; you will want to write a "swap" function to keep your code legible...

It is usually a good idea, when you want to keep a bunch of related items together in an array, to declare a structure. In your case, this structure might look like this:

typedef struct {
  char first_name[32];
  char last_name[32];
  char phone_number[16];
} entry;

Then you can declare your phone book as

entry phoneBook[100];

which would create enough space for 100 phonebook entries.

Finally, when you go through the list of entries, you might modify your bubble sort like this (assuming that n = number of entries):

for ( int i=0; i < n - 1; i++ )
{
  for ( int j = i; j < n; j++ )
  {
    if (strcmpi(entries[j].first_name, entries[j+1].first_name) > 0)
    {
      swap(entries, j, j+1);
    }
  }
}

And finally you would have a swap function like this:

void swap(entry* e, int i, int j) {
// swap all elements of e[i] and e[j]
  entry temp;
  strcpy(temp.first_name,   e[i].first_name);
  strcpy(temp.last_name,    e[i].last_name);
  strcpy(temp.phone_number, e[i].phone_number;
  strcpy(e[i].first_name,   e[j].first_name);
  strcpy(e[i].last_name,    e[j].last_name);
  strcpy(e[i].phone_number, e[j].phone_number;
  strcpy(e[j].first_name,   temp.first_name);
  strcpy(e[j].last_name,    temp.last_name);
  strcpy(e[j].phone_number, temp.phone_number;
}
Floris
  • 45,857
  • 6
  • 70
  • 122