Complexity of Programs 303
Complexity of Selection
Let n E N. Let a step of an algorithm be to make a selection for execution of one of
n blocks, B 1 , B 2 ... , Bn, and, on input I, where each Bi executes the key operations
at most Fi (Bi) times for 1 < i < n and it then takes G(I) executions of the key op-
erations to make the selection of the block to execute. Then, the key operations are
executed at most
G(I) +-max{Fi(Bl), F 2 (B 2 ). Fn (Bn)}
times.
The next algorithm also sorts a three-element list. To some people, it is more obvi-
ous than the preceding algorithm, since it breaks the algorithm down into the six possible
cases, asking first which element is least. For easy reference to individual lines of the al-
gorithm, we put line numbers on the left ends of the lines. We assume the procedure Swap
interchanges the values of the two elements that are in the storage locations named by its
arguments.
INPUT: Distinct values for three variables A, B, and C
OUTPUT: The list of values in increasing order
- if(C <AandC<B) then
- if(A <B) then /C<A <B, so!
- Swap(A, B)
- Swap(A, C)
- else / C < B < A, so/
- Swap (C, A)
- else
- if(B < A and B < C) then
- if(A <C) then /B <A<C, so/
- Swap (A, B)
- else / B < C < A, so/
- Swap (A, B)
- Swap (B, C)
- else
- if (C < B) then / A < C < B, so/
- Swap (B, C)
- print A, B, C
This algorithm nests selections within selections within selections. The outermost
selection is in line 1, with its corresponding false range beginning at line 6. We will