Module 6 · 16 min read · Free chapter
Searching and sorting
Binary search finds a key in a sorted array in Θ(log n). Insertion sort is Θ(n²) in the worst case but Θ(n) on sorted input. Merge sort is always Θ(n log n) and stable, quicksort averages Θ(n log n) but worst case is Θ(n²), and heapsort is Θ(n log n) in place.
Start from zero: the reservation chart
Picture the reservation chart pasted on a train coach at the platform. If the 72 names on it are in random order, you must read them one by one until you find your own. If the chart is sorted by name, you can jump to the middle, see whether your name comes before or after, and ignore half the chart at once.
That small difference is the whole subject of this chapter. Searching means finding an item, and it becomes far faster when the data is sorted. Sorting itself takes work, so we also need good ways to put data in order.
Every sorting method answers the same question in a different way: which item goes where, and how many comparisons and moves does that take? Some methods are simple but slow, some are fast but need extra memory, and some keep equal items in their original order while others do not.
Why it matters. Banks sort transactions, railways sort waiting lists and search engines sort results, millions of times a day. GATE asks almost every year about comparison counts, stability and worst cases, so knowing each method's habits is worth real marks.
Linear search and binary search
Linear search starts at the first element and compares each element with the key until it finds a match or reaches the end. It needs no order in the data and works on arrays and linked lists alike. Its worst case is comparisons, when the key is last or absent, so it is .
Binary search needs two things: the array must be sorted, and we must be able to jump to any index in one step. It compares the key with the middle element. If they are equal, we stop; if the key is smaller, we keep only the left half, and otherwise only the right half.
low = 0; high = n - 1
while (low <= high) {
mid = low + (high - low) / 2
if (a[mid] == key) return mid
else if (a[mid] < key) low = mid + 1
else high = mid - 1
}
return -1 // not found
Each probe throws away about half of the remaining range, so after probes about elements remain. The search ends when the range is empty, which gives at most probes. For that is at most 10 probes, and for at most 20 probes.
Worked example. Search for 23 in the sorted array 2, 5, 8, 12, 16, 23, 38, 56, 72, 91, with indices 0 to 9. The first mid is , where is smaller than 23, so low becomes 5. The next mid is , where is larger, so high becomes 6; then mid = 5 and , found in 3 probes.
Writing instead of is a small habit worth keeping. When low and high are both large, their sum can overflow a fixed-size integer, while the difference cannot.
Why it matters. Binary search is the reason we sort data that is searched often. A phone's contact list, a dictionary app and a database index all depend on the same halving idea.
The three simple sorts: bubble, selection and insertion
We will trace all three on the array 5, 2, 4, 6, 1, 3, so that their habits are easy to compare. Each of them takes time in the worst case, but they differ in comparisons, swaps and best cases.
Bubble sort walks through the array and swaps every adjacent pair that is out of order. After the first pass the largest element, 6, has "bubbled" to the last position, and after pass the last elements are final. Without any check it makes comparisons, which is 15 for .
A common improvement keeps a flag that records whether a pass made any swap. If a whole pass makes no swap, the array is already sorted and the method stops. On a sorted input this gives one pass of comparisons, so the best case drops to .
Selection sort finds the minimum of the unsorted part and swaps it to the front of that part. On our array the first pass scans all six and swaps 1 with 5, giving 1, 2, 4, 6, 5, 3. It always makes comparisons, even on sorted input, but it makes at most swaps, which helps when writing to memory is costly.
Selection sort is not stable. Take 4a, 4b, 1, where 4a and 4b are equal keys from different records. The first pass swaps 1 with 4a and gives 1, 4b, 4a, so the two equal keys have changed their order.
Insertion sort works like arranging playing cards in your hand. It takes each new element and shifts the larger elements of the sorted part one place right until the new element fits. On our array, 2 slides before 5, then 4 slides between 2 and 5, and 6 stays where it is.
The number of shifts insertion sort makes equals the number of inversions, the pairs with . Our array has 9 inversions, so insertion sort makes exactly 9 shifts. A sorted array has 0 inversions and needs only comparisons, while a reverse-sorted array has the maximum, .
| Method | Comparisons (worst) | Swaps or shifts (worst) | Best case | Stable? |
|---|---|---|---|---|
| Bubble with flag | yes | |||
| Selection | no | |||
| Insertion | yes |
Why it matters. These simple sorts are still used in practice for small or nearly sorted arrays. Fast library sorts often switch to insertion sort for pieces of about 10 to 20 elements, because it has tiny overheads and runs in almost linear time on data that is nearly in order.
The fast sorts: merge sort, quicksort and heap sort
To beat , a sort must avoid comparing every pair. The three standard ways to do this are merging, partitioning and using a heap, and each one reaches by a different road.
Merge sort splits the array into two halves, sorts each half recursively and then merges the two sorted halves. Merging is like combining two sorted queues: compare the two front elements, move the smaller one out, and repeat. Two sorted lists of sizes and need at most comparisons to merge, because each comparison sends out one element and the last element needs no comparison.
Merge sort does the same splitting on every input, so it is in the best, average and worst case. Its weak point is memory, because merging arrays needs a temporary array. It is stable as long as the merge takes from the left half when two keys are equal.
Quicksort does the hard work before the recursive calls. It picks a pivot, rearranges the array so that smaller elements come before it and larger elements after it, and then sorts the two parts. In the Lomuto scheme, with the last element as pivot, the array 7, 2, 1, 6, 8, 5, 3, 4 becomes 2, 1, 3, 4, 8, 5, 7, 6, and 4 is now in its final place.
If the pivot splits the array roughly in half each time, quicksort takes . But if the pivot is always the smallest or largest element, one part is empty and the other has elements, so the time becomes . This happens, for example, on an already sorted array when the first or last element is the pivot.
Quicksort sorts in place apart from its recursion stack, and in practice it is often the fastest of the three because its inner loop is very simple. It is not stable, because partitioning swaps elements over long distances. Choosing the pivot at random makes the bad case very unlikely for every input, as the divide and conquer analysis shows.
Heap sort uses a max-heap, a complete binary tree stored in an array where every parent is at least as large as its children. Building the heap from the array takes time. Then the method swaps the root, which is the maximum, with the last element, shrinks the heap by one and restores the heap order in , and it does this times.
So heap sort is in the worst case and needs only extra space. It is not stable, and it is usually slower than quicksort in practice because it jumps around memory. The heap itself is covered with binary heaps.
Why it matters. Each fast sort wins somewhere. Merge sort suits linked lists and huge files on disk, quicksort suits arrays in memory, and heap sort suits systems that need a firm worst case with no extra memory.
Sorting without comparisons: counting sort and radix sort
All the sorts so far learn about the data only by comparing two keys. If the keys are small integers, we can do better by using the key itself as an array index, just as a teacher returns answer sheets by dropping each into the pile for its roll number.
Counting sort assumes the keys lie in the range 0 to . It counts how many times each value occurs in an array C of size , then turns the counts into running totals, so that tells how many keys are at most v. Finally it walks the input from right to left and places each key at position , reducing by one each time.
The total time is and the extra space is also . This is linear when is , for example when sorting the marks of 10 lakh students out of 100. The right-to-left final pass is what makes counting sort stable, and stability is exactly what radix sort needs.
Radix sort sorts keys digit by digit, starting from the least significant digit. Each pass uses a stable sort, usually counting sort, on one digit. Take 512, 147, 368, 903, 254, 731, 186: sorting by units, then tens, then hundreds gives 147, 186, 254, 368, 512, 731, 903.
For keys of d digits in base b, radix sort takes time. For example, 32-bit integers can be split into four 8-bit digits, so and , and the sort takes four linear passes. When d is a constant, radix sort is linear in .
These methods do not break the lower bound of the next section, because they do not sort by comparisons. They use the structure of the keys instead, so they need integer keys or keys that can be turned into digits.
Why it matters. Counting and radix sort power fast work on fixed-length keys such as PIN codes, roll numbers, dates and IP addresses. Exams like to ask why they are not and why radix sort needs a stable inner sort.
Stability, in-place sorting and the n log n lower bound
Two properties decide which sort to use when time is similar. A sort is stable if records with equal keys stay in their original relative order. Suppose a list of passengers is already sorted by name and you now sort it by coach number with a stable sort; within each coach the names stay in alphabetical order.
A sort is in-place if it needs only extra memory besides the array, and most authors allow the recursion stack of quicksort as well. Merge sort on arrays and counting sort are not in-place, because they need extra arrays of size or .
| Method | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Bubble (with flag) | 1 | yes | |||
| Selection | 1 | no | |||
| Insertion | 1 | yes | |||
| Merge | yes | ||||
| Quick | (stack) | no | |||
| Heap | 1 | no | |||
| Counting | yes | ||||
| Radix | yes |
Now the deepest fact of the chapter: no comparison-based sort can beat in the worst case. Any such sort can be drawn as a decision tree, where each inner node is one comparison and each leaf is one final order. The tree must have a leaf for every one of the possible orders of the input.
A binary tree of height has at most leaves, so and . Since , the worst-case number of comparisons is . So merge sort and heap sort are asymptotically optimal comparison sorts.
Worked example. How many comparisons must any method make, in the worst case, to sort 4 elements? There are orders and , so at least 5 comparisons are needed.
For 5 elements, and , so at least 7.
Why it matters. The lower bound tells you when to stop looking for a faster comparison sort and start looking at the keys instead. It is also a model for how computer scientists prove that a problem is hard, and not just that a method is slow.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about searching and sorting in four ways:
- Trace a named sort on a given array and show the array after each pass.
- Compare sorts on time, space, stability and best and worst cases, usually in a table.
- Prove a bound, such as the lower bound or the worst case of quicksort.
- Choose a sort for a stated situation and justify the choice, for example nearly sorted data or very little memory.
Practice questions (our own, not previous-year questions).
- Trace insertion sort on 8, 3, 5, 1, 9, 2 and count the shifts. Relate the count to the number of inversions. (10 marks)
- Explain why quicksort is in the worst case and suggest two ways to avoid that case in practice. (10 marks)
- Prove that every comparison-based sorting algorithm needs comparisons in the worst case. (15 marks)
Answer plan for question 3.
- Model any comparison sort as a binary decision tree in which each inner node compares two elements and each leaf gives one output order.
- State that a correct sort must reach a different leaf for each of the orders of distinct inputs, so the tree has at least leaves.
- Note that a binary tree of height has at most leaves, so and .
- Show that , so , which is .
- Conclude that the height, which equals the worst-case number of comparisons, is .
- Remark that merge sort and heap sort meet this bound, while counting and radix sort avoid it by not comparing keys.
Quick revision
- Linear search works on any list and takes up to comparisons.
- Binary search needs a sorted array with index access and takes at most probes.
- Bubble, selection and insertion sort are in the worst case and in-place.
- Selection sort makes at most swaps but always comparisons.
- Insertion sort's work equals plus the number of inversions, so it is fast on nearly sorted data.
- Merge sort is in every case, stable, and needs extra space.
- Quicksort is on average but in the worst case, and it is not stable.
- Heap sort is in the worst case, in-place and not stable.
- Counting sort is , and radix sort is with a stable sort on each digit.
- Every comparison sort needs comparisons in the worst case, because the decision tree has leaves.