9.4Insertion Sort and Bubble Sort
Covers IGNOU MCS-208 §9.5, 9.5.1, 9.5.2
Sorting puts records in order of their keys. This page introduces two simple methods that are easy to understand and good for small or nearly sorted data, and the important idea of a stable sort.
Internal sorting and stability
In internal sorting all records fit in main memory; external sorting (the last section) handles files that do not.
Stability matters when records are sorted on one key after another (for example by name, then by city): a stable second sort keeps the first order among equal cities.
Insertion sort
For : take ; shift every element of the sorted part that is larger than one place right; put into the gap. (Unit 1 analyses it exactly.)
- Best case (already sorted): comparisons, .
- Worst case (reverse order): comparisons, ; average also .
- Stable (it shifts only strictly larger elements), in place.
Bubble sort
In each pass, compare neighbouring elements from the end of the array towards the front and swap them if they are out of order; the smallest remaining element “bubbles up” to the front. After pass the first elements are in their final places.
- Comparisons: , i.e. .
- With a flag that stops when a pass makes no swap, an already sorted array needs only one pass: .
- Stable only if equal neighbours are not swapped.
Key takeaways
- Internal sorting: all data in memory. Stable: equal keys keep their order.
- Insertion sort: insert each element into the sorted prefix; best, worst/average; stable.
- Bubble sort: swap out-of-order neighbours in passes; ; best with an early-exit flag.
- Use
<, not<=, so equal keys are not swapped.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Sort 34 8 64 51 32 21 using insertion sort, showing the array after each insertion, and state the number of comparisons in the worst case for 6 elements.
Show worked answer
Insert 8: 8 34 64 51 32 21. Insert 64: 8 34 64 51 32 21. Insert 51: 8 34 51 64 32 21. Insert 32: 8 32 34 51 64 21. Insert 21: 8 21 32 34 51 64. Worst case (reverse order): comparisons, so the method is .