Example. Time complexity of searching and sorting

[comp1110-2F]
  • Linear search through an array of \(n\) elements: If the target happens to be the first element, the algorithm stops immediately; this is the best case and takes constant time, \(\mathrm {O}(1)\). In the worst case the element is last or not present, so the algorithm must check all \(n\) elements. The worst-case running time is therefore \(\mathrm {O}(n)\).
  • Binary search on a sorted array. Each comparison eliminates half of the remaining elements. After one step at most \(\frac {n}{2}\) elements remain, then \(\frac {n}{4}\), then \(\frac {n}{8}\), and so on. After about \(\log _2 n\) steps only one element remains. Thus binary search runs in \(\mathrm {O}(\log n)\) time in the worst case.
  • Selection sort repeatedly scans the remaining part of the array to find the smallest element. Even if the array is already sorted, it still performs the same number of comparisons, roughly \(\frac {n(n-1)}{2}\). Its running time therefore grows like \(n^2\), so it is \(\mathrm {O}(n^2)\) in both the best and worst cases.
  • Insertion sort behaves differently. If the array is already sorted, each new element is compared once and left in place, so the running time grows linearly: \(\mathrm {O}(n)\). But if the array is in reverse order, each insertion shifts many elements and the total work grows like \(n^2\). Thus the best case is \(\mathrm {O}(n)\) and the worst case is \(\mathrm {O}(n^2)\).
  • Bubble sort with early exit is similar. If the list is already sorted, it finishes after one pass, which is \(\mathrm {O}(n)\). In the worst case — where one small element appears out of order towards the end of the list — it performs many passes and becomes \(\mathrm {O}(n^2)\).
  • Merge sort works differently. It divides the list in half, sorts each half, and then merges them. The list can be halved only about \(\log _2 n\) times, and each level of this process requires work proportional to \(n\) to perform the merges. The total work therefore grows like \(n \log n\). Unlike some previous sorts, this running time does not depend on the initial order of the input: both the best and worst cases are \(\mathrm {O}(n \log n)\).
bars magnifying-glass caret-down plus minus arrow-right xmark