Skip to main content

Posts

Showing posts with the label sorting a linked list

Merge sort a linked list

Sorting a linked list is much more complex than sorting an array. Because you need to be wary of links at each step and update them. The most convenient ways of sorting a linked list is insertion sort, where in you remove one node at a time from list and insert them to the sorted list in correct position. But merge sorting a linked list uses another approach. It splits the list into two halves, sorts them recursively and then merges them maintaining ascending order of key values. So the three basic parts of this approach are Splitting the list into two halves of equal length Sorting these halves Merging the halves Step 2 is in fact not needed if the list has only one node. One node is sorted. Hence the merge sort algorithm is If the list has more than one node Splitting the list into two halves of equal length Sorting these halves recursively using steps 2 to 4 Merging the halves   Split the list into halves We have seen in this post how to find the m...