Greedy Algorithms
Figure 16.1 shows the operation of the algorithm. In a given recursive call RECURSIVE-ACTIVITY-SELECTOR(s, f, i, j), the while loop of lines 2-3 looks for the first activity in Sij. The loop examines ai 1, ai 2, ..., aj-1, until it finds the first activity am that is compatible with ai; such an activity has sm ≥ fi. If the loop terminates because it finds such an activity, the procedure returns in line 5 the union of {am} and the maximum-size subset of Smj returned by the recursive call RECURSIVE-ACTIVITY-SELECTOR(s, f, m, j). Alternatively, the loop may terminate because m ≥ j, in which case we have examined all activities whose finish times are before that of aj without finding one that is compatible with ai. In this case, Sij = Ø, and so the procedure returns Ø in line 6.
Assuming that the activities have already been sorted by finish times, the running time of the call RECURSIVE-ACTIVITY-SELECTOR(s, f, 0, n 1) is Θ(n), which we can see as follows. Over all recursive calls, each activity is examined exactly once in the while loop test of line 2. In particular, activity ak is examined in the last call made in which i < k.