Computer Science and IT‹›⌂ 0:00 studied

Module 6 · 16 min read · Free chapter

Searching and sorting

In short

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.

What are you preparing for? We show the practice and previous year questions of your exam.

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 nn comparisons, when the key is last or absent, so it is Θ(n)\Theta(n).

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 kk probes about n2k\dfrac{n}{2^k} elements remain. The search ends when the range is empty, which gives at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes. For n=1,000n = 1{,}000 that is at most 10 probes, and for n=106n = 10^6 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 0+92=4\dfrac{0 + 9}{2} = 4, where a[4]=16a[4] = 16 is smaller than 23, so low becomes 5. The next mid is 5+92=7\dfrac{5 + 9}{2} = 7, where a[7]=56a[7] = 56 is larger, so high becomes 6; then mid = 5 and a[5]=23a[5] = 23, found in 3 probes.

Writing mid=low+high−low2\mathit{mid} = \mathit{low} + \dfrac{\mathit{high} - \mathit{low}}{2} instead of low+high2\dfrac{\mathit{low} + \mathit{high}}{2} 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 Θ(n2)\Theta(n^2) 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 ii the last ii elements are final. Without any check it makes (n−1)+(n−2)+⋯+1=n(n−1)2(n - 1) + (n - 2) + \dots + 1 = \dfrac{n(n - 1)}{2} comparisons, which is 15 for n=6n = 6.

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 n−1n - 1 comparisons, so the best case drops to Θ(n)\Theta(n).

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 n(n−1)2\dfrac{n(n - 1)}{2} comparisons, even on sorted input, but it makes at most n−1n - 1 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 i<ji < j with a[i]>a[j]a[i] > a[j]. Our array has 9 inversions, so insertion sort makes exactly 9 shifts. A sorted array has 0 inversions and needs only n−1n - 1 comparisons, while a reverse-sorted array has the maximum, n(n−1)2\dfrac{n(n - 1)}{2}.

Method Comparisons (worst) Swaps or shifts (worst) Best case Stable?
Bubble with flag n(n−1)2\dfrac{n(n - 1)}{2} n(n−1)2\dfrac{n(n - 1)}{2} Θ(n)\Theta(n) yes
Selection n(n−1)2\dfrac{n(n - 1)}{2} n−1n - 1 Θ(n2)\Theta(n^2) no
Insertion n(n−1)2\dfrac{n(n - 1)}{2} n(n−1)2\dfrac{n(n - 1)}{2} Θ(n)\Theta(n) 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 n2n^2, 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 Θ(nlog⁡n)\Theta(n \log n) 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 mm and nn need at most m+n−1m + n - 1 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 Θ(nlog⁡n)\Theta(n \log n) in the best, average and worst case. Its weak point is memory, because merging arrays needs a Θ(n)\Theta(n) 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 Θ(nlog⁡n)\Theta(n \log n). But if the pivot is always the smallest or largest element, one part is empty and the other has n−1n - 1 elements, so the time becomes Θ(n2)\Theta(n^2). 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 O(n)O(n) 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 O(log⁡n)O(\log n), and it does this n−1n - 1 times.

So heap sort is Θ(nlog⁡n)\Theta(n \log n) in the worst case and needs only O(1)O(1) 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 nn keys lie in the range 0 to kk. It counts how many times each value occurs in an array C of size k+1k + 1, then turns the counts into running totals, so that C[v]C[v] tells how many keys are at most v. Finally it walks the input from right to left and places each key at position C[key]C[\mathit{key}], reducing C[key]C[\mathit{key}] by one each time.

The total time is Θ(n+k)\Theta(n + k) and the extra space is also Θ(n+k)\Theta(n + k). This is linear when kk is O(n)O(n), 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 nn keys of d digits in base b, radix sort takes Θ(d(n+b))\Theta(d(n + b)) time. For example, 32-bit integers can be split into four 8-bit digits, so b=28=256b = 2^8 = 256 and d=4d = 4, and the sort takes four linear passes. When d is a constant, radix sort is linear in nn.

These methods do not break the nlog⁡nn \log n 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 Θ(nlog⁡n)\Theta(n \log n) 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 O(1)O(1) extra memory besides the array, and most authors allow the O(log⁡n)O(\log n) recursion stack of quicksort as well. Merge sort on arrays and counting sort are not in-place, because they need extra arrays of size nn or kk.

Method Best Average Worst Extra space Stable
Bubble (with flag) nn n2n^2 n2n^2 1 yes
Selection n2n^2 n2n^2 n2n^2 1 no
Insertion nn n2n^2 n2n^2 1 yes
Merge nlog⁡nn \log n nlog⁡nn \log n nlog⁡nn \log n nn yes
Quick nlog⁡nn \log n nlog⁡nn \log n n2n^2 log⁡n\log n (stack) no
Heap nlog⁡nn \log n nlog⁡nn \log n nlog⁡nn \log n 1 no
Counting n+kn + k n+kn + k n+kn + k n+kn + k yes
Radix d(n+b)d(n + b) d(n+b)d(n + b) d(n+b)d(n + b) n+bn + b yes

Now the deepest fact of the chapter: no comparison-based sort can beat nlog⁡nn \log n 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 n!n! possible orders of the input.

A binary tree of height hh has at most 2h2^h leaves, so 2h≥n!2^h \ge n! and h≥log⁡2(n!)h \ge \log_2(n!). Since log⁡2(n!)=Θ(nlog⁡n)\log_2(n!) = \Theta(n \log n), the worst-case number of comparisons is Ω(nlog⁡n)\Omega(n \log n). 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 4!=244! = 24 orders and log⁡224≈4.58\log_2 24 \approx 4.58, so at least 5 comparisons are needed.

For 5 elements, 5!=1205! = 120 and log⁡2120≈6.9\log_2 120 \approx 6.9, 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:

  1. Trace a named sort on a given array and show the array after each pass.
  2. Compare sorts on time, space, stability and best and worst cases, usually in a table.
  3. Prove a bound, such as the Ω(nlog⁡n)\Omega(n \log n) lower bound or the worst case of quicksort.
  4. 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).

  1. Trace insertion sort on 8, 3, 5, 1, 9, 2 and count the shifts. Relate the count to the number of inversions. (10 marks)
  2. Explain why quicksort is Θ(n2)\Theta(n^2) in the worst case and suggest two ways to avoid that case in practice. (10 marks)
  3. Prove that every comparison-based sorting algorithm needs Ω(nlog⁡n)\Omega(n \log n) 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 n!n! orders of distinct inputs, so the tree has at least n!n! leaves.
  • Note that a binary tree of height hh has at most 2h2^h leaves, so 2h≥n!2^h \ge n! and h≥log⁡2(n!)h \ge \log_2(n!).
  • Show that n!≥(n2)n2n! \ge (\dfrac{n}{2})^{\frac{n}{2}}, so log⁡2(n!)≥(n2)log⁡2(n2)\log_2(n!) \ge (\dfrac{n}{2}) \log_2(\dfrac{n}{2}), which is Ω(nlog⁡n)\Omega(n \log n).
  • Conclude that the height, which equals the worst-case number of comparisons, is Ω(nlog⁡n)\Omega(n \log n).
  • 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 nn comparisons.
  • Binary search needs a sorted array with index access and takes at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes.
  • Bubble, selection and insertion sort are Θ(n2)\Theta(n^2) in the worst case and in-place.
  • Selection sort makes at most n−1n - 1 swaps but always n(n−1)2\dfrac{n(n - 1)}{2} comparisons.
  • Insertion sort's work equals nn plus the number of inversions, so it is fast on nearly sorted data.
  • Merge sort is Θ(nlog⁡n)\Theta(n \log n) in every case, stable, and needs Θ(n)\Theta(n) extra space.
  • Quicksort is Θ(nlog⁡n)\Theta(n \log n) on average but Θ(n2)\Theta(n^2) in the worst case, and it is not stable.
  • Heap sort is Θ(nlog⁡n)\Theta(n \log n) in the worst case, in-place and not stable.
  • Counting sort is Θ(n+k)\Theta(n + k), and radix sort is Θ(d(n+b))\Theta(d(n + b)) with a stable sort on each digit.
  • Every comparison sort needs Ω(nlog⁡n)\Omega(n \log n) comparisons in the worst case, because the decision tree has n!n! leaves.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 14 answered

  1. Binary search can be applied directly only when the data is:

  2. The maximum number of probes binary search makes on a sorted array of 1,000 elements is:

  3. Bubble sort with an early-exit flag, run on an already sorted array of nn elements, makes:

  4. Which sort makes at most n−1n - 1 swaps on any input of nn elements?

  5. The best-case number of comparisons of selection sort on nn elements is:

  6. How many shifts does insertion sort make on the array 5, 2, 4, 6, 1, 3?

  7. For which input does insertion sort take Θ(n2)\Theta(n^2) time?

  8. The maximum number of comparisons needed to merge two sorted lists of sizes 6 and 4 is:

  9. Quicksort with the last element as pivot, run on an already sorted array, takes:

  10. Building a max-heap from an unsorted array of nn elements takes:

  11. Counting sort on nn keys in the range 0 to kk takes:

  12. Radix sort needs the sort used on each digit to be:

  13. Which of these sorts is stable?

  14. The minimum number of comparisons any comparison sort needs in the worst case to sort 5 elements is at least:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

Which sorting algorithms are stable?

Insertion sort, bubble sort and merge sort are stable. Selection sort, quicksort and heapsort, in their usual forms, are not.

When does quicksort take Θ(n²) time?

When every pivot is the smallest or largest element, for example the first element as pivot on already sorted input.

Why can no comparison sort beat n log n?

A decision tree must have at least n! leaves, so its height is at least log₂ n!, which is Θ(n log n).

How many comparisons does binary search need for 1,000 elements?

At most 10 in the worst case, because each comparison halves the range and 2¹⁰ = 1,024 is more than 1,000.

More in this module: Algorithms

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Algorithms (IIT Kharagpur, 106105164): searching, sorting and lower bounds
  3. NPTEL Programming, Data Structures and Algorithms (CMI, 106106145): searching and sorting