【问题标题】:How to sort the implemented list data structure in descending order?如何对实现的列表数据结构进行降序排序?
【发布时间】:2019-05-23 15:41:17
【问题描述】:

我需要按降序对列表进行排序。我该怎么做 ? 我有以下课程:

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

所以该方法必须具有以下签名

List Sorted(List x)

因此它返回另一个包含 x 元素的 List,但按降序排序。头部必须包含最大的元素。 我该如何实现呢?

【问题讨论】:

标签: c# list sorting


【解决方案1】:

希望对你有帮助

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

或使用排序

var objectordered = object.Sort((obj1,obj2) => obj1.Desc.CompareTo(obj2.Desc));

【讨论】:

  • 但是如果禁止使用 LINQ 或 Sort 方法怎么办。我的意思是我想得到算法解决方案
  • 这听起来有点像学校作业。如果您不打算使用 LINQ,那么您唯一的选择是通过循环执行此操作,就像您使用数组执行此操作一样。 1. 创建一个与初始数组大小相同的临时数组 2. 从源数组的末尾循环(循环到开头)并将值复制到临时数组中(从开头开始循环到结尾) 3. 退出循环并使源数组等于临时数组
【解决方案2】:

这是一个低效的实现,比bubble sort 慢。它对作为参数提供的列表进行就地排序,它不会创建列表的排序副本。如果需要创建副本,您可能需要自己实现复制。

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;
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多