What sorting algorithm can be used to sort a linked list?
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?Why is Quick Sort preferred for arrays? Show Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for array.
Why is Merge Sort preferred for Linked Lists? Below are implementations of Quicksort and Mergesort for singly and doubly linked lists. Quick Sort for Doubly Linked List
Related Articles:
Thanks to Sayan Mukhopadhyay for providing initial draft for above article. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Article Tags :
Sorting
Linked-List-Sorting Merge Sort Quick Sort Practice Tags :
Sorting Merge Sort
Read Full Article
How to sort a linked list using merge sortMerge sort is one of the most famous divide-and-conquer sorting algorithms. This algorithm can be used to sort values in any traversable data structure (i.e., a linked list). Program to sort the elements of the singly linked listExplanationIn this program, we need to sort the nodes of the given singly linked list in ascending order. Original list: Sorted list: To accomplish this task, we maintain two pointers: current and index. Initially, current point to head node and index will point to node next to current. Traverse through the list till current points to null, by comparing current's data with index's data. If current's data is greater than the index's data, then swap data between them. In the above example, current will initially point to 9 and index will point to 7. Since, 9 is greater than 7, swap the data. Continue this process until the entire list is sorted in ascending order. Algorithm
SolutionPythonOutput: Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9
COutput: Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9
JAVAOutput: Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9
C#Output: Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9
PHPOutput: Original list:
9 7 2 5 4
Sorted list:
2 4 5 7 9
|