VOOZH about

URL: https://dzone.com/articles/sort-linked-list-ascending

⇱ Sort Linked List in Ascending Order - C#


Related

Sort Linked List in Ascending Order - C#

By Jun. 04, 12 · Code Snippet
Likes
Comment
Save
22.1K Views

Join the DZone community and get the full member experience.

Join For Free

Sort Linked List in Ascending Order - C#

Efficiency: O(n^2)

Inspired by Selection Sort algorithm

/// 
 /// head node of unsorted linked list
 /// number of elements in unsorted linked list
 /// 
 public static Node SortLinkedList(Node head, int count)
 {
 // Basic Algorithm Steps
 //1. Find Min Node
 //2. Remove Min Node and attach it to new Sorted linked list
 //3. Repeat "count" number of times

 Node _current = head;
 Node _previous = _current;

 Node _min = _current;
 Node _minPrevious = _min;

 Node _sortedListHead = null;
 Node _sortedListTail = _sortedListHead;

 for (int i = 0; i < count; i++)
 {
 _current = head;
 _min = _current;
 _minPrevious = _min;

 //Find min Node
 while (_current != null)
 {
 if (_current.Data < _min.Data)
 {
 _min = _current;
 _minPrevious = _previous;
 }
 _previous = _current;
 _current = _current.Next;
 }

 // Remove min Node 
 if (_min == head)
 {
 head = head.Next;
 }
 else if (_min.Next == null) //if tail is min node
 {
 _minPrevious.Next = null;
 }
 else
 {
 _minPrevious.Next = _minPrevious.Next.Next;
 }


 //Attach min Node to the new sorted linked list
 if (_sortedListHead != null)
 {
 _sortedListTail.Next = _min;
 _sortedListTail = _sortedListTail.Next;
 }
 else
 {
 _sortedListHead = _min;
 _sortedListTail = _sortedListHead;
 }
 }

 return _sortedListHead;
 }
Sort (Unix)

Opinions expressed by DZone contributors are their own.

Related

  • Handle HL7 MLLP Messages With Mule 4
  • What SREs Can Learn From Capt. Sully: When To Follow Playbooks
  • Amazon Dynamo DB Connector Operations Walkthrough in Mule 4, Part 1
  • Comparing SQL and SPL: Order-Based Computations

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: