Sorting a Common Linked List

I have everything in a generic list, except for sorting. And I don’t know how to use IComparable or how I will do it because it is common. I don’t know what I would even compare or sort?

 public class Node<T> : IComparable<T> { private Node<T> next; private T item; } 

So,

 public int CompareTo( T other ) { // TODO: Find out how to do it properly throw new NotImplementedException(); } 

It is also against instructions to convert it to an array, then sort it and then convert it back.

+5
source share
2 answers

Having a linked Node list, implementing an IComparable object makes absolutely no sense for the exact reasons you describe. Instead, the classes you use in a linked list should implement it. In fact, you can require this with a general type constraint:

 MyClass<T> where T : IComparable<T> {} 

In doing so, you can use T as if there were a IComparable when executing your view.

+6
source

The first thing you need to do is read the sorting algorithms and decide which one you are going to use. Once you do this, you can worry about comparing your common values.

If you want to follow a framework approach, don't require your T to implement IComparable<T>. Use Comparer<T>.Default . This approach allows you to write your own class to support custom comparisons:

 public class LinkedList<T> { public void Sort() { this.Sort(Comparer<T>.Default); } public void Sort(IComparer<T> comparer) { //todo: implement throw new NotImplementedException(); } } 

In my original version of this answer, there was a resolver as a class property, but this is really wrong because the linked list is not sorted by default. You can sort the list once once, and then after 2 seconds, sort it differently. Therefore, the comparator must be a parameter of the sorting method.

+1
source

Source: https://habr.com/ru/post/1200622/


All Articles