Sub topic 10
Stability, In-Place Sorting, and Adaptivity
This chapter assumes you can read the insertion, selection, and bubble sort code from the previous chapter and that you know big-O notation. Running time is one way to compare sorting algorithms. Three other properties often decide which one to use, and GATE asks about them directly: stability, in-place behavior, and adaptivity.
Definitions
A sort is stable if records with equal keys keep their original relative order in the output. If two records both have key 5 and record X came before record Y in the input, X still comes before Y after sorting.
A sort is in-place if it uses only O(1) extra memory beyond the input array, apart from a few variables. Some texts relax this to O(log n) so that recursive quick sort counts. Check which definition a question uses.
A sort is adaptive if its running time improves when the input is already partly ordered. The usual test is whether it runs in O(n) on sorted input.
Stability only matters when records carry more than the key. Sorting plain integers, you cannot tell equal values apart. Sorting students by marks, you can.
Why stability matters
Suppose a list is sorted by name, and you then sort it by department. A stable sort leaves each department's students in name order. An unstable sort may scramble them.
This gives the standard way to sort by several keys. Sort by the least significant key first, then by the next, ending with the most significant key. Each pass must be stable. Radix sort works this way, which is why counting sort must be stable when used as its subroutine.
Seeing the properties in code
The program below sorts records by their number only. The letter shows the original order of equal keys. It also counts the element shifts insertion sort performs on different inputs.
def insertion_sort(a, key=lambda x: x):
shifts = 0
for i in range(1, len(a)):
cur = a[i]
j = i - 1
while j >= 0 and key(a[j]) > key(cur):
a[j + 1] = a[j]
j -= 1
shifts += 1
a[j + 1] = cur
return shifts
def selection_sort(a, key=lambda x: x):
for i in range(len(a) - 1):
m = i
for j in range(i + 1, len(a)):
if key(a[j]) < key(a[m]):
m = j
a[i], a[m] = a[m], a[i]
first = key = lambda r: r[0]
data = [(2, "a"), (2, "b"), (1, "c")]
s = list(data)
selection_sort(s, key)
print("selection:", s)
t = list(data)
insertion_sort(t, key)
print("insertion:", t)
print("shifts, sorted input: ", insertion_sort([1, 2, 3, 4, 5]))
print("shifts, reversed input:", insertion_sort([5, 4, 3, 2, 1]))The output is:
selection: [(1, 'c'), (2, 'b'), (2, 'a')]
insertion: [(1, 'c'), (2, 'a'), (2, 'b')]
shifts, sorted input: 0
shifts, reversed input: 10Selection sort swaps (2, 'a') with (1, 'c'). That swap carries a past b, so the order of the equal keys flips. Insertion sort only moves an element past strictly greater ones, so equal keys never cross. If you change > to >= in the while condition, insertion sort becomes unstable.
Insertion sort does 0 shifts on sorted input and n(n−1)/2 = 10 shifts on reversed input of size 5. Its running time is proportional to n plus the number of inversions, so it is O(n) on sorted data and Θ(n²) in the worst case.
Summary of the common algorithms
| Algorithm | Stable | In-place | Adaptive | Extra space |
|---|---|---|---|---|
| Insertion sort | Yes | Yes | Yes, O(n) best case | O(1) |
| Selection sort | No (swap version) | Yes | No, always Θ(n²) comparisons | O(1) |
| Bubble sort | Yes | Yes | Yes only with an early-exit flag | O(1) |
| Merge sort | Yes (take left on ties) | No | No in the standard form | O(n) |
| Quick sort (Lomuto) | No | Yes (by the O(log n) definition) | No | O(log n) average stack |
| Heap sort | No | Yes | No | O(1) |
| Counting sort | Yes (backward scan) | No | No | O(n + k) |
Two entries need explanation.
- Bubble sort without a flag always makes Θ(n²) comparisons. With a flag that stops after a pass with no swaps, it needs one pass on sorted input, so it is O(n).
- Quick sort is in-place because partitioning swaps elements within the array. Its recursion stack uses O(log n) on average and O(n) in the worst case, unless you recurse into the smaller part first.
Where instability comes from
Instability arises when an operation moves an element across a distance, jumping over equal keys. Selection sort's swap, quick sort's partition swaps, and heap sort's extract-max swap all do this.
You can make any sort stable by pairing each record with its original index and comparing indexes on equal keys. This costs O(n) extra space, so the sort is no longer in-place.
Trade-offs
- Merge sort guarantees Θ(n log n) and is stable, but it needs O(n) extra space. It suits linked lists and external sorting.
- Heap sort gives Θ(n log n) in the worst case with O(1) space, but it is neither stable nor adaptive.
- Quick sort is fast in practice and in-place, but it is unstable and has a Θ(n²) worst case.
- Insertion sort is the best choice for small or nearly sorted arrays. Practical hybrids, such as Python's Timsort, use it for short runs and are stable and adaptive.
Common mistakes
- Calling merge sort in-place. The merge step needs an auxiliary array of size n.
- Calling an algorithm adaptive because its best case is fast on some input. The test is whether it benefits from existing order, such as sorted input.
- Ignoring the recursion stack. A recursive algorithm that allocates nothing explicit still uses stack space.
- Assuming stability matters for plain numbers. It matters only when records carry other data.
Exercise
An array of records is sorted by key using the standard heap sort. The input has two records with key 7, X before Y. Can Y appear before X in the output? Name the step responsible.
Show answer
Yes. Heap sort is not stable. Building the heap and repeatedly swapping the root with the last element moves records across long distances, so equal keys can cross. For example, extract-max swaps the root with a leaf that may hold an equal key.
Exercise
A sorted array of n elements is given to insertion sort, to selection sort, and to bubble sort with an early-exit flag. How many comparisons does each make, in big-O terms, and which are adaptive?
Show answer
Insertion sort makes n−1 comparisons, so it is O(n). Bubble sort with the flag makes one pass of n−1 comparisons, so it is O(n). Selection sort makes n(n−1)/2 comparisons, so it is Θ(n²). Insertion sort and flagged bubble sort are adaptive. Selection sort is not.