Computer Science · B2.4 · SL and HL

Big O notation, searching and sorting

In the new guide, searching and sorting come with their complexity: you are expected to trace binary search, write bubble sort, and say why one algorithm is O(n2)O(n^2) and another O(logn)O(\log n). Stating the Big O is usually worth one mark, and the second mark is for the reason, taken from the structure of the code.

Written from the stages “Big O notation”, “Linear and binary search” and “Bubble sort and selection sort” of the 7Quest Computer Science course. The questions are our own, in the style of the exam; none are from past papers.

What Big O measures

Timing a program tells you about the computer, the language and whatever else was running, not about the algorithm. So instead we count how many operations it performs as a function of the input size nn, and look at how that number grows as nn gets large. Big O describes that growth as an upper bound, and in the exam it means the worst case unless you are told otherwise. Constants and smaller terms are dropped: 3n2+5n+203n^2 + 5n + 20 is O(n2)O(n^2).

Five classes cover almost everything: O(1)O(1) for indexing a list or pushing onto a stack, O(logn)O(\log n) for binary search, O(n)O(n) for linear search or summing a list, O(nlogn)O(n \log n) for efficient sorts such as merge sort, and O(n2)O(n^2) for bubble sort, selection sort and most nested loops. If nn goes from 1000 to 1,000,000, an O(n)O(n) algorithm takes 1000 times longer, an O(n2)O(n^2) one a million times longer, and an O(logn)O(\log n) one goes from about 10 steps to about 20.

Space complexity is the same idea for the extra memory used, not counting the input. Sorting in place by swapping is O(1)O(1) in space; building a copy of the list is O(n)O(n).

Reading complexity from code

A fixed number of statements is O(1)O(1), even if the fixed number is 10. A loop that runs nn times with an O(1)O(1) body is O(n)O(n). Nested loops multiply, so two loops over nn are O(n2)O(n^2); that stays true when the inner loop gets shorter each time, because n+(n−1)+⋯+1=n(n+1)2n + (n - 1) + \dots + 1 = \frac{n(n+1)}{2} is still of order n2n^2. A loop that halves the problem each time (n = n // 2) runs about log2n\log_2 n times, so it is O(logn)O(\log n). Consecutive blocks add, and the largest one wins: an O(n)O(n) loop followed by an O(n2)O(n^2) one is O(n2)O(n^2).

The justification is what earns the second mark: “there are two nested loops that each go through the list, so the comparison runs of the order of n×nn \times n times, which is O(n2)O(n^2)”.

Linear and binary search

Linear search checks each element in turn until it finds the target or reaches the end. It works on any list, sorted or not. The best case is the target in first place, O(1)O(1); the worst is the target last or missing, O(n)O(n).

Binary search needs a sorted list. It keeps a range from low to high, compares the target with the middle element v[mid], where mid = (low + high) // 2, and throws away the half that cannot contain it: low = mid + 1 if the middle value is too small, high = mid - 1 if it is too big. When low > high the range is empty and the target is not there. Each comparison halves the range, so the worst case is about log2n\log_2 n comparisons: at most 10 for 1000 elements and 20 for a million.

The usual bugs are low = mid (an infinite loop), while low < high (the last element is never checked), / instead of // (a decimal index) and running it on an unsorted list. For a trace, draw columns for low, high, mid, v[mid] and the outcome, one row per comparison, and show the final values when the target is missing.

Bubble sort and selection sort

Bubble sort compares each pair of adjacent elements and swaps them if they are in the wrong order. After the first pass the largest value has moved to the end, after the second the second largest, and n−1n - 1 passes are always enough. The worst case, a list in reverse order, needs n(n−1)2\frac{n(n-1)}{2} comparisons, so it is O(n2)O(n^2). With a swapped flag the algorithm stops after a pass with no swaps, so an already sorted list takes one pass of n−1n - 1 comparisons: O(n)O(n) in the best case.

Selection sort finds the minimum of the unsorted part and swaps it into the first unsorted position, so after pass ii the first ii positions are final. It always makes n(n−1)2\frac{n(n-1)}{2} comparisons, best case and worst case alike, so it is O(n2)O(n^2) either way, but it makes at most n−1n - 1 swaps, which helps when writing to memory is expensive. Both sorts are in place and use O(1)O(1) extra space.

Count comparisons from the code you are given. If the inner loop does not get shorter each pass, a 5-element list takes 4 passes of 4 comparisons, which is 16, not 10.

Where the marks go

  • Giving the Big O without the reason. Point at the loops: how many there are, whether they are nested, and how far each one runs.
  • Calling a loop that runs a fixed 100 times O(n)O(n). If the number of iterations does not depend on nn, it is O(1)O(1).
  • Using binary search on an unsorted list, or forgetting to say that sorting is its precondition.
  • Writing mid = (low + high) / 2 in Python, which gives a float, or updating with low = mid instead of mid + 1.
  • Saying selection sort is O(n)O(n) on a sorted list. It still scans the whole unsorted part every pass.

Three questions to try

Answer on paper first, then open the markscheme and mark yourself honestly. A mark only counts if your answer says that point.

Determine3 marksPaper 2 style

The function below counts the pairs of values in a list that add up to target.
(a) State how many times the condition v[i] + v[j] == target is evaluated when v has 6 elements. [1]
(b) Determine the worst-case time complexity of the function in Big O notation, justifying your answer. [2]

def count_pairs(v, target):
    count = 0
    for i in range(len(v)):
        for j in range(i + 1, len(v)):
            if v[i] + v[j] == target:
                count += 1
    return count
Show the markscheme

Markscheme (3 marks)

  1. (a) 5 + 4 + 3 + 2 + 1 + 0 = 15 [1]
  2. (b) O(n2)O(n^2) [1]
  3. (b) Nested loops over the list: the condition is evaluated n(n−1)2\frac{n(n-1)}{2} times, which grows with n2n^2 (constants and lower-order terms are dropped) [1]

A full-marks answer

(a) When i is 0 the inner loop runs 5 times, then 4, 3, 2, 1 and 0 times, so the condition is evaluated 15 times.
(b) The function is O(n2)O(n^2). There are two nested loops that each go through the list, and although the inner loop gets shorter each time, the condition is evaluated n(n−1)2\frac{n(n-1)}{2} times in total. That is of order n2n^2 once the constant 12\frac{1}{2} and the lower-order term are dropped.

Trace5 marksPaper 2 style

The list v = [3, 8, 12, 19, 24, 31, 40, 47, 55] is searched with the function below.
(a) Trace binary_search(v, 20), showing the values of low, high, mid and v[mid] at each comparison, and the value returned. [4]
(b) State the maximum number of comparisons this function needs for a sorted list of 1000 elements. [1]

def binary_search(v, target):
    low = 0
    high = len(v) - 1
    while low <= high:
        mid = (low + high) // 2
        if v[mid] == target:
            return mid
        elif v[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
Show the markscheme

Markscheme (5 marks)

  1. (a) low = 0, high = 8, mid = 4, v[mid] = 24; 24 > 20 so high = 3 [1]
  2. (a) low = 0, high = 3, mid = 1, v[mid] = 8; 8 < 20 so low = 2; then low = 2, high = 3, mid = 2, v[mid] = 12; low = 3 [1]
  3. (a) low = 3, high = 3, mid = 3, v[mid] = 19; 19 < 20 so low = 4 [1]
  4. (a) low = 4 > high = 3, so the loop ends and the function returns −1 [1]
  5. (b) 10 [1]

A full-marks answer

(a) First comparison: low = 0, high = 8, mid = 4, v[mid] = 24. Since 24 > 20, high = 3.
Second: low = 0, high = 3, mid = 1, v[mid] = 8. Since 8 < 20, low = 2.
Third: low = 2, high = 3, mid = 2, v[mid] = 12. Since 12 < 20, low = 3.
Fourth: low = 3, high = 3, mid = 3, v[mid] = 19. Since 19 < 20, low = 4.
Now low = 4 and high = 3, so low <= high is false, the loop ends and the function returns −1: 20 is not in the list.
(b) Each comparison halves the range and 210=1024>10002^{10} = 1024 > 1000, so at most 10 comparisons are needed.

Compare4 marksPaper 2 style

A program keeps a list of 10,000 scores that is almost always sorted, with only one or two new values out of place. Compare bubble sort with a swapped flag and selection sort for sorting this list.

Show the markscheme

Markscheme (4 marks)

  1. Both are O(n2)O(n^2) in the worst case and both sort in place with O(1)O(1) extra space [1]
  2. Bubble sort with a flag stops after a pass with no swaps, so on an (almost) sorted list it needs only one or a few passes: close to O(n)O(n) [1]
  3. Selection sort always makes n(n−1)2\frac{n(n-1)}{2} comparisons, about 50 million for 10,000 elements, whatever the order of the data [1]
  4. So bubble sort with a flag is the better choice here; selection sort’s advantage (at most n−1n - 1 swaps) matters little when few elements are out of place [1]

A full-marks answer

Both algorithms are O(n2)O(n^2) in the worst case and both sort the list in place, using O(1)O(1) extra memory. The difference is how they behave on data that is already nearly sorted. Bubble sort with a swapped flag stops as soon as a whole pass makes no swaps, so if only one or two values are out of place it finishes after a few passes of 9,999 comparisons each, which is close to linear. Selection sort cannot stop early: it scans the whole unsorted part on every pass and always makes 10 000×9 9992=49 995 000\frac{10\,000 \times 9\,999}{2} = 49\,995\,000 comparisons. Selection sort does make fewer swaps in general, at most n−1n - 1, but here bubble sort would make very few swaps anyway, so bubble sort with a flag is clearly the better choice.

Where this is in 7Quest

It is in Algorithm Engine, the part of the Computer Science map for Data structures, algorithms and files:

  • Big O notationSyllabus B2.4.1 · 2 exam-style questions
  • Linear and binary searchSyllabus B2.4.2 · 3 exam-style questions
  • Bubble sort and selection sortSyllabus B2.4.3 · 3 exam-style questions

Each stage has a short lesson, quick questions, a minigame and exam-style questions marked point by point, and what you get wrong comes back in your review a few days later. If this is the topic you find hardest, you can choose Data structures, algorithms and files as your free Computer Science topic and do all of it without paying or giving a card. Full access is a subscription per subject that renews each September and stops after your final exams, so nothing is charged once you have finished (prices and details).

Questions students ask about this

Which complexities do I need for IB Computer Science?

The five classes on this page: O(1)O(1), O(logn)O(\log n), O(n)O(n), O(nlogn)O(n \log n) and O(n2)O(n^2), for both time and space, with the best and worst cases of the searches and sorts.

Do I need to know quicksort or merge sort?

You need quicksort if you take HL, where it comes with recursion. Linear search, binary search, bubble sort and selection sort are for SL and HL, and at SL it is enough to know that efficient sorts are O(nlogn)O(n \log n).

Can I write the algorithms in Java instead of Python?

Yes. The guide allows Python or Java for Paper 2, and the algorithms are the same. In Java, (low + high) / 2 with int operands is already integer division.