0

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

1 Answers1

1

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • 1
    @Lunar If you want to use your function, just do `sorted.CompareTo2(newnode) > 0`, or ` < 0`, depending on your desired sort order. – JonasH Jun 21 '22 at 08:23
  • @Lunar if you are just starting out I would reemphasize the importance of the debugger, it is just super helpful. And it was unfortunately not taught well when I went to school. – JonasH Jun 21 '22 at 08:36
  • I will definitely look into it, they haven't really gone in-depth with it for us as well so I had to stick to looking up the error codes so far. –  Jun 21 '22 at 08:55