Which of the following sorting techniques is not preferred 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 Merge Sort for Linked Lists
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let the head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so the head node has to be changed if the data at the original head is not the smallest value in the linked list. MergeSort(headRef) 1) If the head is NULL or there is only one element in the Linked List then return. 2) Else divide the linked list into two halves. FrontBackSplit(head, &a, &b); /* a and b are two halves */ 3) Sort the two halves a and b. MergeSort(a); MergeSort(b); 4) Merge the sorted a and b (using SortedMerge() discussed here) and update the head pointer using headRef. *headRef = SortedMerge(a, b);Which sorting is best for doubly linked list?What is the best sorting algorithm for a doubly linked list? Insertion sort and merge sort appears to the best due to the less overhead compared to the bubble/selection sort. How do you quick sort using doubly linked list?The idea is simple, we first find out pointer to the last node. Once we have a pointer to the last node, we can recursively sort the linked list using pointers to first and last nodes of a linked list, similar to the above recursive function where we pass indexes of first and last array elements. |