Skip to interview prep
Apexed

98. What is the best way to sort a linked list, and why merge sort rather than quicksort or heapsort?

MediumLinked lists

Technical

Type or dictate your answer. Your draft is saved on this device.

Show model answer

Merge sort fits linked lists: split the list at the middle with slow/fast pointers, sort both halves recursively, and merge them by relinking nodes. That is O(n log n) time, needs no extra arrays because merging is in place, and is stable. The recursive version uses O(log n) stack; a bottom-up version merging runs of size 1, 2, 4, ... uses O(1) extra space.

Quicksort relies on random access for good pivots and partitioning, and heapsort needs indexed parent/child access, which costs O(n) per jump on a list. Copying to an array, sorting and rebuilding also works in O(n log n) but uses O(n) extra memory.

Example program

What is the best way to sort a linked list, and why merge sort rather than quicksort or heapsort — Data structures & algorithms interview question — Apexed