0

Possible Duplicate:
Sort a single linked list

What will be the sorting algorithm code to sort a singly linked list in the following form after the nodes inserted and I am finished with it? I have tried bubble sort but I could not achieve..

    struct WordCounter {
        char *word;
        int word_count;
        struct WordCounter *pNext;  /* pointer to the next word counter in the list */
    };
Community
  • 1
  • 1
dante deo
  • 63
  • 1
  • 1
  • 13

2 Answers2

0

Why use a custom linked list when the standard library has an std::list template class? Replace your struct with

struct WordCounter {
    std::string word;
    unsigned word_count;
};

Stick these in an std::list<WordCounter> and use its sort member function.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • I am not familiar with std::list class. Even if I change the struct, I do not know how to change the rest of my code populating the list :S – dante deo Dec 28 '11 at 20:49
  • @user1119900 Docs for std::list are here http://stdcxx.apache.org/doc/stdlibref/list.html . It even comes with a sort() routine that you can use. – nsanders Dec 28 '11 at 20:56
0

It would depend on many things. I am assuming you have a task that requires you to implement the sort by yourself.

  1. The size of the linked list. Insertionsort fares well with linked lists of moderate size. Otherwise quicksort should do the trick.
  2. The distributions of "word_count" which I am assuming you are sorting on.
  3. The requirements for your task. Is standard sorting i.e. std::sort acceptable?

For the problem I am reading between the lines a std::map pair< word_count, word> > would be the c++ way to go.

Or quite possibly an insertion sort if this is a school project, and you have not still covered Quicksort.

The most relevant response to your question is "What have you tried?", this is not an easy task. You have both the linked list concepts as well as the sorting concepts to sort out and get a hang of.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67