-2

I need to sort list in descending order. How can I do it ? I've got the following class:

class Node
{
    public int data;
    public Node next; 
}
class List
{
    public Node head;
}

So the method has to have the following signature

List Sorted(List x)

So that it returns another List containing x's elements, but sorted in descending order. Head must contain the biggest element. How can I implement that ?

  • You can use `list.OrderByDescending();` [see here](https://www.tutorialsteacher.com/linq/linq-sorting-operators-orderby-orderbydescending) – Matheus Dasuke May 23 '19 at 15:55
  • Possible duplicate of [Sorting a linked list](https://stackoverflow.com/questions/768095/sorting-a-linked-list) or [Sortable linked list of objects](https://stackoverflow.com/q/7623356/150605) – Lance U. Matthews May 23 '19 at 18:54

2 Answers2

0

I hope this help you

var objectordered = object.OrderBy(o => o.Desc).ToList();

or using Sort

var objectordered = object.Sort((obj1,obj2) => obj1.Desc.CompareTo(obj2.Desc));
pnet
  • 258
  • 1
  • 17
  • But what if it's forbidden to use LINQ or Sort method. I mean I want to get algorithmic solution – Dima Glushenkov May 23 '19 at 15:55
  • This sounds eerily like a school assignment. If you aren't going to use LINQ, then your only option is to do it via a loop the same way you would do it with an array. 1. create a temp array the same size as initial array 2. loop from the end of the source array (looping toward the beginning) and copy the value into the temp array (starting from the beginning and looping toward the end) 3. Exit loop and make source array equal to temp array – Joel Priddy May 23 '19 at 16:12
0

Here is an inefficient implementation, slower than bubble sort. It sorts in-place the list supplied as argument, it does not create a sorted copy of the list. If creating a copy is necessary, you may need to implement the copying yourself.

void Sort(List x)
{
start:
    Node current = x.head;
    Node previous = null;
    while (current != null && current.next != null)
    {
        if (StringComparer.Ordinal.Compare(current.data, current.next.data) < 0)
        {
            // Swap current and current.next nodes
            // We need to change three references
            if (previous != null)
            {
                previous.next = current.next;
            }
            else
            {
                x.head = current.next;
            }
            var temp = current.next.next;
            current.next.next = current;
            current.next = temp;
            goto start; // Restart the loop
        }
        // Advance previous and current references
        previous = current;
        current = current.next;
    }
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104