Sub topic 1
What Sorting Means: Order, Keys, and In-Place Comparison Sorts
Bubble sort, selection sort, and insertion sort all solve the same problem. Before looking at how each one works, you need a precise statement of that problem and the rules the three algorithms follow. This chapter supplies both.
Prerequisites
This chapter assumes you can:
- Write loops and conditionals in a language such as Python.
- Read and write list or array elements by index, for example
a[i]anda[i + 1]. - Read Big-O notation such as O(n) and O(n²).
The Sorting Problem
A sorting algorithm takes a sequence a of n elements and rearranges it so that a[0] <= a[1] <= ... <= a[n-1]. A correct output must meet two conditions:
- It is ordered. Each element is less than or equal to the one after it. This is called nondecreasing order. "Increasing" would be wrong here because equal values are allowed to sit next to each other.
- It is a permutation of the input. The output holds exactly the same elements, duplicates included, and nothing else.
A common mistake is to check only the first condition. A function that returns an empty list, or that removes duplicates, produces ordered output and still fails as a sort.
from collections import Counter
def is_sorted(a):
return all(a[i] <= a[i + 1] for i in range(len(a) - 1))
def is_valid_sort(original, result):
return is_sorted(result) and Counter(original) == Counter(result)
data = [3, 1, 2, 3]
print(is_valid_sort(data, [1, 2, 3, 3])) # True
print(is_valid_sort(data, sorted(set(data)))) # False: a duplicate was lost
print(is_valid_sort(data, [])) # False: ordered, but not a permutationKeys and Records
Real programs rarely sort bare numbers. They sort records, such as rows, objects, or tuples, by one field of each record called the key. Sorting students by score compares only the scores and moves the whole records.
records = [("bob", 82), ("ann", 95), ("cy", 82)]
by_score = sorted(records, key=lambda r: r[1]) # returns a new list
print(by_score) # [('bob', 82), ('cy', 82), ('ann', 95)]
print(records) # [('bob', 82), ('ann', 95), ('cy', 82)] unchanged
records.sort(key=lambda r: r[1]) # rearranges records in place
print(records) # [('bob', 82), ('cy', 82), ('ann', 95)]Two records can have equal keys and still be different records. In the example, bob and cy both scored 82. Whether a sort keeps such records in their original relative order is a property called stability, which a later chapter covers. For now, note that a sorted output can be correct by key while the records with equal keys appear in more than one possible order.
Comparison Sorts
A comparison sort learns about the elements only by asking whether one key is less than another. It never looks at a key's digits or bits. Because of this, the same code can sort integers, strings, dates, or any type that defines a consistent order.
For a comparison sort to behave predictably, the comparison must be a total order. Every pair of keys must be comparable, and if x <= y and y <= z, then x <= z. Floating-point NaN breaks this rule, because every comparison involving it returns false. That is why sorting a list containing NaN can give output that looks partly unsorted.
In-Place Sorting
A sort is in place when it rearranges the input array itself and uses only O(1) extra memory beyond it, meaning a few index and temporary variables. Bubble, selection, and insertion sort are all in place. They move elements by swapping two positions or by shifting a run of elements one slot over. Merge sort is a comparison sort that is usually not in place, because it needs an O(n) auxiliary buffer.
All three algorithms take O(n²) time in the worst case. They differ in how many comparisons they make, how many writes they perform, and how they handle input that is already nearly sorted. The next chapter defines exactly how to count that work.
Exercise
The input is [4, 2, 4, 1]. A function returns [1, 2, 4]. Which of the two correctness conditions does this output fail, and why?
Show answer
It is in nondecreasing order, but it is not a permutation of the input. One of the two 4s is missing, so the multiset of elements changed.
Exercise
You sort a list of (name, age) tuples by age with a comparison sort. Two people are both 30. Is the result incorrect if their order differs from the input order?
Show answer
No. The output is still correctly sorted by key. Whether equal-keyed records keep their original order is a separate property (stability), and a sort can be correct without being stable.
Exercise
An algorithm copies the input into a new array of size n, sorts the copy, and copies it back. Is it in place?
Show answer
No. It uses O(n) auxiliary memory. An in-place sort uses only O(1) extra space beyond the input array.