hello. I have to use a function in my phonebook program to sort the names alphabitcally
here is what i have done so far.but what's wrong with it?

void showAllContacts() {    
    char t[40];
    list *head;
    if(head == NULL) {
        puts("There are no contacts to display!");
    } else {
        printf("\nAll contacts:\n");

     /* Set the temp pointer to point to the first record in the
        list. */
        list *temp = head;

        /* Loop through all the nodes in the linked list and print
           out all the corresponding name and phone records. */
        while(temp!= NULL){
            if(strcmp(temp->name,temp->next->name) > 0) {
                strcpy(t, temp->name);
                strcpy(temp->name, temp->next->name);
                strcpy(temp->next->name, t);
                cout<<temp->name<<temp->tel;
            }
            //else {
             //printf("%-20s %-9s\n", temp->name,temp->tel);
            //}

            temp=temp->next;
        }


    }
}

If you have the option, sorting the names as you add them would most likely be a better option.

What you've got seems to introduce but not use 't', and has a bug on line 16 (when temp->next is NULL).

Also, you are endeavoring to do two things at once: sort and display. Don't do that. Put the sort stuff in its own function.

Sorting is not particularly easy, but the simplest sort you might employ over a singly-linked list is called insertion sort.

You'll need two lists -- an empty one (new_head) and the one you wish to sort (head).

While there are elements in head pop off the first one.

Find where it belongs in new_head and insert it there. (You should have a function to insert a node in your list, right?)

When you are done, just return the new_head list from the function.

(And yes, this is an N-squared algorithm, but for your homework lists you shouldn't notice.)

Hope this helps.

Try to use std::sort.

If C, then use quicksort. If C++, then std::sort works, but quicksort is also good, and efficient.

Neither std::sort() nor quicksort are appropriate for sorting a linked list.

Further, homeworks typically expect you to do the sorting yourself.

Try to use std::sort with std:list ;-)
timnased didn't said this was a homework, he just said he is making a phonebook program.

You go try to use std::sort with std::list first.

And this is a very obvious homework problem, either from an actual school or from a book.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.