Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Sort Linked List in Ascending Order - C#

· ·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Sort Linked List in Ascending Order - C#

Efficiency: O(n^2)

Inspired by Selection Sort algorithm

///
/// This method sorts elements in linked list and returns a new sorted linked list
///
/// number of elements in unsorted linked list
///

{
// 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 _previous = _current;

Node _min = _current;
Node _minPrevious = _min;

for (int i = 0; i < count; i++)
{
_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
{
}
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
{
_sortedListTail.Next = _min;
_sortedListTail = _sortedListTail.Next;
}
else
{
}
}

}
Topics:

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.