Search code examples
c#algorithmdata-structureslinked-list

How to implement Insertion Sorting on a Linked List String Alphabetically


I haven't found any information on this, how can I implement insertion sorting on a string with Linked Lists. I have been able to create the Linked List however I cannot figure out how to implement the sorting part.

I also want to be able to sort by first name and last name but first I need to figure out how to sort by the first name...

Here is what I have reached so far.

removed code for now

Any help would be greatly appreciated.

Thanks


Solution

  • There are some apparent issues:

    if (this.lastName.CompareTo(another.LastName) < 0)
         return -1;
    else
         if (this.lastName.CompareTo(another.LastName) == 0)
               return this.firstName.CompareTo(another.FirstName);
    

    Why are you starting by comparing lastnames if you wanted to primarily sort by firstname?

    sorted.val >= newnode.val
    

    Why are you sorting by a value if you wanted to sort by name? Just call your comparison function if you want to compare nodes by the first/last name.

    The rest of the code looks ok for a learning exercise as far as I can see. If you have issues I would recommend to

    1. Write unit tests! It becomes much easier to find bugs when you can run several sets of test-data to your algorithm designed to find various edge cases. Especially for something like sorting where it is trivial to verify your result.
    2. Learn how to use the debugger. The behavior of the program becomes much easier to understand when you can stop at various points and verify that the variables match your expectation.

    See How to debug small programs for more details.

    Writing code like this can be very useful as a learning exercise, but please do not use code like this for anything serious. There is perfectly fine sorting functions built into the framework that will be both faster and easier to understand. Also note that linked lists are rarely used in real life, I do not think I have used one even once outside of school. See also we must avoid linked lists.