What are Sorting Algorithms?
Algorithms·7 min·Python code
Sorting algorithms arrange a list in order, and your choice depends on speed, memory and stability. Merge and heap sort guarantee O(n log n) time, the lowest bound for comparison sorting, and quick sort matches it on average.
Five Sorting Algorithms You Should Know
Bubble and insertion sort are the two quadratic methods. Bubble sort walks the list and swaps neighbours that sit out of order, so the largest value drifts to the end on every pass. Insertion sort grows a sorted prefix by sliding new values back into place, like ordering cards in your hand.
Both cost O(n²) time. Insertion sort still handles tiny or nearly sorted input well, so real libraries switch to it for short subarrays.
Merge sort splits the array in half, sorts both halves and joins them with the two pointers technique. It stays stable, costs O(n log n) in every case and needs O(n) extra space.
Quick sort chooses a pivot and partitions values into smaller and larger groups, then sorts both groups. It works in place and suits real arrays, yet a poor pivot drags it down to O(n²).
Heap sort builds on the heap data structure and extracts the maximum again and again to fill the array from the back. Time stays O(n log n) whatever the input, with O(1) extra space. Heap sort is not stable, and it jumps around memory, so quick sort beats it in practice.
Stable Sorting and Why the Order of Equals Matters
A sort is stable when equal elements keep their original order. Sort users by name and then by age with a stable sort, and every age group stays alphabetical for free.
Merge sort, insertion sort and bubble sort are stable. Standard quick sort and heap sort are not.
Python's sorted() and list.sort() use Timsort, a stable hybrid of merge sort and insertion sort. Interviewers who ask you to sort by several keys expect you to name a stable method or sort by a tuple of keys.
Why O(n log n) Limits Comparison Sorting Algorithms
No comparison sort beats O(n log n) in the worst case, and the limit is proven. Sorting by comparing pairs forms a decision tree, and telling apart n! possible orderings needs at least n! leaves. That tree has a height of at least log₂(n!), which grows as n log n.
Merge and heap sort reach that bound, so no comparison sort improves on them.
Skip comparisons and the bound no longer applies. Counting sort, radix sort and bucket sort reach linear time when keys are small integers or fixed width values. Name them when an interviewer asks how to beat O(n log n).
Practise every method on CodeStory's sorting practice problems.
Merge Sort Code Example in Python
def merge_sort(nums):
if len(nums) <= 1:
return nums # 0 or 1 element is already sorted
mid = len(nums) // 2
left = merge_sort(nums[:mid]) # sort both halves recursively
right = merge_sort(nums[mid:])
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= preserves order of equals (stable)
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
merged.extend(left[i:]) # append whatever remains
merged.extend(right[j:])
return merged
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Sorting Algorithms Time and Space Complexity
| Time | O(n log n) for merge, heap and average case quick sort. O(n²) for bubble, insertion and worst case quick sort |
|---|---|
| Space | O(1) for bubble, insertion and heap sort. O(n) for merge sort. O(log n) stack for quick sort |
Cases differ. Insertion sort reaches O(n) on nearly sorted data, quick sort averages O(n log n) but hits O(n²) with poor pivots, and merge and heap sort stay at O(n log n) every time.
Watch Sorting Algorithms Step by Step
Seeing values swap on your own input makes the differences between sorts clear. Follow any of these one step at a time.
When to Use Which Sorting Algorithm
- You need a guaranteed O(n log n) worst case with stable output, so choose merge sort or a library Timsort.
- Input is small or nearly sorted, where insertion sort does the job with little code.
- You must sort in place with O(1) extra memory and a firm worst case bound, which points to heap sort.
- You want low average time on in memory arrays and can guard against bad pivots, so quick sort fits.
Mistakes to Avoid
- Assuming quick sort is always O(n log n), because a naive pivot drops sorted or reverse sorted input to O(n²). Real code randomises the pivot or falls back to heap sort.
- Forgetting that quick sort and heap sort are not stable, so sorting by a second key scrambles ties. Use a stable sort or sort by a tuple of keys.
- Writing a sort by hand when the language built in is correct and already tuned, so hand roll one only when the question asks for it.
Sorting Algorithms FAQs
What is the time complexity of sorting algorithms?
Bubble and insertion sort cost O(n²). Merge sort, heap sort and average case quick sort cost O(n log n). Comparison sorts cannot beat O(n log n), while counting sort and radix sort reach O(n) on small integer keys.
Which sorting algorithm should I use?
No single method wins. Quick sort has low overhead and cache friendly access on in memory arrays. Merge sort wins when you need stability or a firm worst case, and insertion sort wins on tiny or nearly sorted input.
Do I need to memorise every sorting algorithm for interviews?
No. Write merge sort and quick sort from scratch and explain heap sort. Interviewers test complexities, stability and when sorting is the right tool, and watching the sorts move step by step makes those points stick.
What is a stable sorting algorithm?
Stable sorts keep equal elements in their original order. That matters when you sort records by date without scrambling an earlier alphabetical order. Insertion sort and merge sort are stable, while typical quick sort and heap sort are not.
Why is quick sort O(n²) in the worst case?
Bad pivots leave one side empty and the other side one value smaller, so the recursion goes n levels deep and does O(n) work at every level. Sorted input with a first or last element pivot triggers this. Random pivots avoid it.
Which sorting algorithm does Python use?
Python uses Timsort in sorted() and list.sort(). Timsort is a stable hybrid of merge and insertion sort that costs O(n log n) at worst and O(n) on sorted input.
How do I practise sorting algorithms on CodeStory?
Watch bubble sort, insertion sort, merge sort and quick sort move on your own input in CodeStory's visualisers, then write the code yourself in the CodeStory app.
Related Guides
Guides are step one. In a CodeStory batch you code the sorts yourself, then explain every swap in a scored mock round.
Talk to a Mentor