Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

sorting - C# - Sort items of linked list by date

I am having a Node

public class Node
{
    public Node(Pupil pupil)
    {
        Data = pupil;
        Next = null;
    }
    public Pupil Data { get; set; }
    public Node Next { get; set; }
}

which holds the date of birth of a student. I insert objects to the list like this

public void Insert(Pupil pupil)
{
    if (_head == null)
    {
        _head = new Node(pupil);
        return;
    }

    Node current = _head;

    while (current.Next != null)
    {
        current = current.Next;
    }

    current.Next = new Node(pupil);
}

But now i have the problem to sort the pupils by date of birth (pupil.DateOfBirth). Since I am new to Lists etc. I dont have an idea how to do this. Since corona is here we have to basically teach it ourselves in university. Help would be really appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Suppose you have an object called unorderedList (containing your pupils in an unordered fashion) and an object called orderedList, which initially is empty. Then you can do the following:

  1. Take an element of unorderedList. It is not important which element you take. For example, you can always take the first one (which is also a good idea if the list is already partially ordered). Let's call this element temp.
  2. Add temp to the correct position of orderedList.
  3. Remove temp from unorderedList.
  4. Do steps 1-3 until unorderedList is empty.

This algorithm is called insertion sort. The Wikipedia article on insertion sort also contains an implementation in C. You could take a look at it to get an idea how you could do it in C#.

Insertion sort is a rather primitive sorting approach. Other approaches (such as quicksort, mergesort, etc.) may be faster, but are also harder to implement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...