Why sorting matters#
Sorted data is easy to search (binary search), find duplicates in, rank, merge and display. Sorting is also the classic way to learn how algorithm design affects speed.
Bubble sort - O(n²)#
Repeatedly swap neighbours that are in the wrong order. After each pass the largest remaining element "bubbles" to the end.
after pass 1: 10 14 29 13 37 after pass 2: 10 14 13 29 37 after pass 3: 10 13 14 29 37 after pass 4: 10 13 14 29 37
Selection sort and insertion sort - O(n²)#
- Selection sort - find the smallest element and put it first, then the next smallest second... Always n²/2 comparisons, few swaps.
- Insertion sort - take each element and insert it into the already-sorted part on its left, like arranging playing cards in your hand. Very fast on nearly sorted data, and used inside real-world sorts for small pieces.
Insertion sort को ताश के पत्तों की तरह समझें। हाथ में पत्ते पहले से क्रम में हैं; नया पत्ता उठाते हैं और उसे सही जगह पर सरका कर डालते हैं - बड़े पत्ते एक-एक जगह दाईं ओर खिसक जाते हैं।
Merge sort - O(n log n), divide and conquer#
- Divide the array into two halves.
- Sort each half recursively.
- Merge the two sorted halves in one linear pass.
3 9 10 27 38 43 82
There are log n levels of splitting, and each level does O(n) merging work → O(n log n). It needs O(n) extra memory and is stable (because of <=).
Quick sort - O(n log n) on average#
Pick a pivot, move smaller elements to its left and bigger ones to its right (partition), then sort both sides recursively.
10 30 40 50 70 80 90
Quick sort is usually the fastest in practice and sorts in place, but a bad pivot (e.g. always the last element of already-sorted data) makes it O(n²). Real libraries pick pivots carefully.
Comparison#
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | O(1) | yes |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | no |
| Insertion | O(n) | O(n²) | O(n²) | O(1) | yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | yes |
| Quick | O(n log n) | O(n log n) | O(n²) | O(log n) | no |
In real code: std::sort#
std::sort (introsort - quick sort + heap sort + insertion sort) is O(n log n) and very fast. Use stable_sort when you need stability.
1 2 5 7 9 9 7 5 2 1 Om Asha Imran Bhavna
Summary#
- Simple sorts (bubble, selection, insertion) are O(n²) - fine for small or nearly sorted data.
- Merge sort: O(n log n) always, stable, needs extra memory.
- Quick sort: O(n log n) on average, in place, O(n²) worst case.
- In C++ use
sort(orstable_sort) with a comparator or lambda.