This last page applies the tools to well-known algorithms and puts them on one “ladder” of growth rates. The tables show, with real numbers, why the step from polynomial to exponential is so dramatic.
Constant-time code
Statements such as x = 4 * y + 3;, z = z + 1; and p = 1; work on single variables. Each takes a fixed number of steps, whatever the values stored, so each is O ( 1 ) O(1) O ( 1 ) , and a fixed sequence of them is also O ( 1 ) O(1) O ( 1 ) . Accessing A[i] in an array is also O ( 1 ) O(1) O ( 1 ) : the address is calculated directly from i.
Binary search: O(log n)
Intuition
To find a word in a dictionary you do not read every page. You open the middle, see whether your word comes before or after, and throw away half the book. Each look halves what is left, so even a 1000-page dictionary needs only about 10 looks.
Definition 1.28 · Binary search
Binary search finds a key in a sorted array by comparing it with the middle element and then continuing only in the half that can still contain the key, until the key is found or the range is empty.
After each comparison the range shrinks from n n n to at most n / 2 n/2 n /2 : the sizes go n , n / 2 , n / 4 , … , 1 n, n/2, n/4, \dots, 1 n , n /2 , n /4 , … , 1 . After k k k halvings the size is about n / 2 k n / 2^k n / 2 k , which reaches 1 when k = log 2 n k = \log_2 n k = log 2 n . Counting the comparison on the final range of size 1, the worst case is ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 comparisons: O ( log n ) O(\log n) O ( log n ) .
Example 1.29 Worst-case steps of binary search
Goal. Count the loop iterations when the key is not in the array (a worst case) for several n n n .
Program. The array holds 0 , 2 , 4 , … 0, 2, 4, \dots 0 , 2 , 4 , … ; the key 2 n 2n 2 n is larger than every element, so it is never found.
C · bsearch_count.c Copy #include <stdio.h>
#define MAX 1000
/* Binary search in a[0..n-1] (sorted). Returns the index of key or -1.
*steps returns how many times the loop body ran. */
int binary_search( const int a [] , int n, int key, int * steps)
{
int low = 0 , high = n - 1 ;
* steps = 0 ;
while (low <= high) {
int mid = low + (high - low) / 2 ; /* avoids overflow of low + high */
( * steps) ++ ;
if (a[mid] == key)
return mid;
else if (a[mid] < key)
low = mid + 1 ; /* key can only be on the right */
else
high = mid - 1 ; /* key can only be on the left */
}
return - 1 ;
}
int main( void )
{
static int a[MAX];
int sizes [] = { 1 , 2 , 7 , 8 , 16 , 1000 };
int steps;
for ( int k = 0 ; k < MAX; k ++ )
a[k] = 2 * k; /* 0, 2, 4, ... (sorted) */
printf( " n steps (key not present, larger than all) \n " );
for ( int s = 0 ; s < 6 ; s ++ ) {
int n = sizes[s];
binary_search(a, n, 2 * n, & steps); /* 2n is bigger than every element */
printf( "%6d %7d \n " , n, steps);
}
return 0 ;
}
Output Copy n steps (key not present, larger than all)
1 1
2 2
7 3
8 4
16 5
1000 10
Compare with the formula. ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 gives 1, 2, 3, 4, 5, 10 for n = 1 , 2 , 7 , 8 , 16 , 1000 n = 1, 2, 7, 8, 16, 1000 n = 1 , 2 , 7 , 8 , 16 , 1000 .
Result. The step counts match ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 ; 1000 elements need at most 10 comparisons.
The travelling salesman problem
Definition 1.30 · Travelling salesman problem (TSP)
Given n n n cities and the distance between every pair, the travelling salesman problem asks for the shortest tour that visits every city exactly once and returns to the start.
The brute-force method tries every tour. How many are there? Fix the starting city (a tour is a cycle, so where it starts does not matter). The remaining n − 1 n - 1 n − 1 cities can be ordered in ( n − 1 ) ! (n - 1)! ( n − 1 )! ways, and each tour is counted twice (once in each direction) when distances are the same both ways. So there are ( n − 1 ) ! 2 \frac{(n-1)!}{2} 2 ( n − 1 )! different tours.
Example 1.31 Counting tours for 5 cities
Goal. Count the different tours through 5 cities A, B, C, D, E.
Fix the start. Start every tour at A; the other 4 cities can be ordered in 4 ! = 24 4! = 24 4 ! = 24 ways.
Remove reversals. A→B→C→D→E→A and A→E→D→C→B→A are the same cycle. Each tour appears twice, so 24 / 2 = 12 24 / 2 = 12 24/2 = 12 .
Compare with n!. 5 ! = 120 5! = 120 5 ! = 120 counts orderings of all 5 cities, which counts each tour 2 × 5 = 10 2 \times 5 = 10 2 × 5 = 10 times.
Result. There are 12 different tours; brute force must check all of them, and the number grows factorially.
Correction · Number of tours in the travelling salesman problem
Study material says: §1.5 says the number of possible tours for n n n cities is “n*(n −1)…*1 = n!”.
Correct version: There are n ! n! n ! orderings of the cities, but only ( n − 1 ) ! 2 \frac{(n-1)!}{2} 2 ( n − 1 )! different tours (for n ≥ 3 n \ge 3 n ≥ 3 with symmetric distances), because the start city and the direction do not change a tour. The conclusion stays the same: the number is factorial, and since ( n − 1 ) ! / 2 ≥ 2 n − 3 (n-1)!/2 \ge 2^{n-3} ( n − 1 )! /2 ≥ 2 n − 3 for n ≥ 3 n \ge 3 n ≥ 3 , brute force needs Ω ( 2 n ) \Omega(2^n) Ω ( 2 n ) time.
Why: Rotating a cycle (choosing a different start) gives n n n copies of each tour and reversing it doubles that, so n ! / ( 2 n ) = ( n − 1 ) ! / 2 n! / (2n) = (n-1)!/2 n ! / ( 2 n ) = ( n − 1 )! /2 . For 5 cities: 120 / 10 = 12 120 / 10 = 12 120/10 = 12 , as counted above.
No algorithm is known that solves TSP exactly in polynomial time (it is NP-hard), so in practice people use heuristics that find good, though not always optimal, tours.
The complexity ladder
Order Name Typical example O ( 1 ) O(1) O ( 1 ) constant Access A[i] in an array O ( log n ) O(\log n) O ( log n ) logarithmic Binary search O ( n ) O(n) O ( n ) linear Loop over all elements of an array (linear search) O ( n log n ) O(n \log n) O ( n log n ) linearithmic Merge sort O ( n 2 ) O(n^2) O ( n 2 ) quadratic Insertion sort (worst case), selection sort O ( n 3 ) O(n^3) O ( n 3 ) cubic Multiplying two n × n n \times n n × n matrices the standard way O ( n k ) O(n^k) O ( n k ) polynomial Any fixed power k k k O ( c n ) O(c^n) O ( c n ) , c > 1 c > 1 c > 1 exponential Trying all 2 n 2^n 2 n subsets of n n n items O ( n ! ) O(n!) O ( n !) factorial Brute-force TSP, trying all orderings
Correction · Complexity of matrix multiplication
Study material says: Table 1.1 (§1.5) lists “matrix multiplication” as an example of O ( n 2 ) O(n^2) O ( n 2 ) , quadratic time.
Correct version: The standard algorithm for multiplying two n × n n \times n n × n matrices is Θ ( n 3 ) \Theta(n^3) Θ ( n 3 ) : each of the n 2 n^2 n 2 entries of the result is a sum of n n n products. Faster methods exist (Strassen’s algorithm, O ( n 2.81 ) O(n^{2.81}) O ( n 2.81 ) ), but none is known to run in O ( n 2 ) O(n^2) O ( n 2 ) .
Why: Three nested loops of n n n iterations each give n ⋅ n ⋅ n n \cdot n \cdot n n ⋅ n ⋅ n multiplications. Cormen et al., Introduction to Algorithms , §4.2, give the standard method as Θ ( n 3 ) \Theta(n^3) Θ ( n 3 ) and Strassen’s as Θ ( n lg 7 ) \Theta(n^{\lg 7}) Θ ( n l g 7 ) .
Two more facts from the study material are worth knowing:
Any sorting algorithm that only compares elements needs Ω ( n log n ) \Omega(n \log n) Ω ( n log n ) comparisons in the worst case, so merge sort is optimal among comparison sorts.
Exponential growth is the dangerous one: such algorithms are usable only for very small inputs.
Note
The study material says algorithms worse than O ( n 2 ) O(n^2) O ( n 2 ) are rarely considered. In practice many useful algorithms are O ( n 3 ) O(n^3) O ( n 3 ) , for example standard matrix multiplication and the Floyd–Warshall shortest-path algorithm in Unit 8; they are fine for a few thousand items.
Example 1.32 Running-time table for different orders
Goal. See how log 2 N \log_2 N log 2 N , N log 2 N N \log_2 N N log 2 N , N 2 N^2 N 2 and 2 N 2^N 2 N grow for real values of N N N .
Program. log2 and pow come from <math.h> (link with -lm).
C · growth_table.c Copy #include <stdio.h>
#include <math.h>
int main( void )
{
double sizes [] = { 8 , 128 , 256 , 1000 , 100000 };
printf( "%8s %8s %10s %16s %16s \n " , "N" , "log2 N" , "N log2 N" , "N*N" , "2^N" );
for ( int k = 0 ; k < 5 ; k ++ ) {
double n = sizes[k];
printf( "%8.0f %8.1f %10.0f %16.0f " , n, log2(n), n * log2(n), n * n);
if (n <= 1000 )
printf( "%16.3g \n " , pow( 2.0 , n));
else /* 2^N is too large for a double: print how many digits it has */
printf( "%9.0f digits \n " , floor(n * log10( 2.0 )) + 1 );
}
return 0 ;
}
Output Copy N log2 N N log2 N N*N 2^N
8 3.0 24 64 256
128 7.0 896 16384 3.4e+38
256 8.0 2048 65536 1.16e+77
1000 10.0 9966 1000000 1.07e+301
100000 16.6 1660964 10000000000 30103 digits
Read the table. Going from N = 8 N = 8 N = 8 to N = 100,000 N = 100{,}000 N = 100 , 000 adds only about 14 to log 2 N \log_2 N log 2 N , while N 2 N^2 N 2 reaches ten billion and 2 N 2^N 2 N becomes a number with 30,103 digits.
Result. At 10 9 10^9 1 0 9 simple steps per second, N 2 N^2 N 2 for N = 100,000 N = 100{,}000 N = 100 , 000 takes about 10 seconds, but 2 N 2^N 2 N for N = 128 N = 128 N = 128 (3.4 × 10 38 3.4 \times 10^{38} 3.4 × 1 0 38 steps) would take far longer than the age of the universe.
Key idea
The order of growth decides what is practical: logarithmic and linear algorithms scale to huge inputs, quadratic ones to moderate inputs, and exponential or factorial ones only to tiny inputs.
TEE Exam note
“Explain the complexity of binary search” (5 marks): describe halving, write the sequence n , n / 2 , n / 4 , … , 1 n, n/2, n/4, \dots, 1 n , n /2 , n /4 , … , 1 , conclude ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 comparisons and O ( log n ) O(\log n) O ( log n ) . “Arrange in increasing order of growth” questions: use the ladder table and name each class. For TSP, give the number of tours, ( n − 1 ) ! 2 \frac{(n-1)!}{2} 2 ( n − 1 )! , and say that no polynomial-time exact algorithm is known.
Common mistake
Using binary search on an unsorted array. Halving only works because sorting tells you which half can contain the key.
Common mistake
Thinking a faster computer fixes an exponential algorithm. A machine 1000 times faster lets a 2 n 2^n 2 n algorithm handle only about 10 more items (2 10 ≈ 1000 2^{10} \approx 1000 2 10 ≈ 1000 ) in the same time.
Key takeaways
A fixed number of simple statements is O ( 1 ) O(1) O ( 1 ) .
Binary search halves the range each step: at most ⌊ log 2 n ⌋ + 1 \lfloor \log_2 n \rfloor + 1 ⌊ log 2 n ⌋ + 1 comparisons, O ( log n ) O(\log n) O ( log n ) .
TSP has ( n − 1 ) ! 2 \frac{(n-1)!}{2} 2 ( n − 1 )! different tours; brute force is factorial and no polynomial exact algorithm is known.
Ladder: 1 < log n < n < n log n < n 2 < n 3 < 2 n < n ! 1 < \log n < n < n\log n < n^2 < n^3 < 2^n < n! 1 < log n < n < n log n < n 2 < n 3 < 2 n < n ! ; standard matrix multiplication is O ( n 3 ) O(n^3) O ( n 3 ) .
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice In the worst case, how many comparisons does binary search need for a sorted array of 1000 elements?
A 9 B 10 C 500 D 1000
Check answer
Show answer Answer: B. 10
⌊ log 2 1000 ⌋ + 1 = 9 + 1 = 10 \lfloor \log_2 1000 \rfloor + 1 = 9 + 1 = 10 ⌊ log 2 1000 ⌋ + 1 = 9 + 1 = 10 (since 2 9 = 512 ≤ 1000 < 1024 2^9 = 512 \le 1000 < 1024 2 9 = 512 ≤ 1000 < 1024 ). 500 would be an average for linear search, not binary search.
Question 2 · multiple choice How many different tours are there for a TSP with 5 cities (symmetric distances)?
A 12 B 24 C 60 D 120
Check answer
Show answer Answer: A. 12
( 5 − 1 ) ! 2 = 24 2 = 12 \frac{(5-1)!}{2} = \frac{24}{2} = 12 2 ( 5 − 1 )! = 2 24 = 12 . 120 is 5 ! 5! 5 ! , which counts each tour 10 times (5 starting cities × 2 directions).
Question 3 · multiple choice An O ( n 2 ) O(n^2) O ( n 2 ) algorithm takes 4 seconds for n = 1000 n = 1000 n = 1000 . About how long will it take for n = 2000 n = 2000 n = 2000 ?
A 4 seconds B 8 seconds C 16 seconds D 64 seconds
Check answer
Show answer Answer: C. 16 seconds
Doubling n n n multiplies n 2 n^2 n 2 by 4: 4 × 4 = 16 4 \times 4 = 16 4 × 4 = 16 seconds. 8 seconds would be the answer for a linear algorithm.
Question 4 · multiple choice What does this program print?
C · q-halving.c Copy #include <stdio.h>
int main( void )
{
int count = 0 ;
for ( int i = 100 ; i > 0 ; i /= 2 )
count ++ ;
printf( "%d \n " , count);
return 0 ;
} A 6 B 50 C 100 D 7
Check answer
Show answer Answer: D. 7
With integer division i takes 100, 50, 25, 12, 6, 3, 1 (seven values), then becomes 0. This is ⌊ log 2 100 ⌋ + 1 = 6 + 1 = 7 \lfloor \log_2 100 \rfloor + 1 = 6 + 1 = 7 ⌊ log 2 100 ⌋ + 1 = 6 + 1 = 7 : a halving loop is O ( log n ) O(\log n) O ( log n ) .
Question 5 · multiple choice What is the time complexity of the standard algorithm for multiplying two n × n n \times n n × n matrices?
Check answer
Show answer Answer: D. O ( n 3 ) O(n^3) O ( n 3 )
There are n 2 n^2 n 2 result entries and each needs n n n multiplications. O ( n 2 ) O(n^2) O ( n 2 ) is only the size of the output, not the work.
Question 6 · short answer
Arrange in increasing order of growth and name each: n ! n! n ! , n log n n \log n n log n , 1 1 1 , 2 n 2^n 2 n , n 2 n^2 n 2 , log n \log n log n , n n n .
Show worked answer 1 1 1 (constant) < log n \log n log n (logarithmic) < n n n (linear) < n log n n \log n n log n (linearithmic) < n 2 n^2 n 2 (quadratic) < 2 n 2^n 2 n (exponential) < n ! n! n ! (factorial).