DAA Module 5
DAA Module 5
▪ Many important algorithms, especially those for sorting and searching, work by
comparing items of their inputs.
▪ We can study the performance of such algorithms with a device called a decision
tree.
▪ Figure 11.1 presents a decision tree of an algorithm for finding a minimum of three
numbers.
▪ Indeed, a binary tree of height h with the largest number of leaves has all
its leaves on the last level (why?).
▪ Hence, the largest number of leaves in such a tree is 2h.
▪ In other words, 2h ≥ l, which immediately implies.
▪ In this section, we shall see how decision trees can be used for
establishing lower bounds on the number of key comparisons in searching
a sorted array of n keys: A[0] < A[1] < ... < A[n 1].
▪ The principal algorithm for this problem is binary search.
▪ The number of comparisons made by binary search in the worst case,
Cbsworst (n), is given by the formula
▪ This inequality closes the gap between the lower bound and the number
of worst- case comparisons made by binary search, which is also
[log2(n+1)] .
▪ A much more sophisticated analysis shows that under the standard
assumptions about searches, binary search makes the smallest number of
comparisons on the average, as well.
▪ The average number of comparisons made by this algorithm turns out to
be about [ log2(n-1) ] and [ log2(n+1) ] for successful and unsuccessful
searches, respectively.
▪ Since each of the four queens has to be placed in its own row, all we need to do is to
assign a column for each queen on the board presented in figure.
▪ Then we place queen 2, after trying unsuccessfully columns 1 and 2, in the first
acceptable position for it, which is square (2, 3), the square in row 2 and column 3.
▪ This proves to be a dead end because there is no acceptable position for queen 3.
▪ So, the algorithm backtracks and puts queen 2 in the next possible position at (2, 4).
▪ Then queen 3 is placed at (3, 2), which proves to be another dead end.
▪ The algorithm then backtracks all the way to queen 1 and moves it to (1, 2).
▪ queen 2 then goes to (2, 4), queen 3 to (3, 1), and queen 4 to (4, 3), which is a
solution to the problem.
▪ Finally, it should be pointed out that a single solution to the n-queens problem for any
n ≥ 4 can be found in linear time.
▪ For example, for A = {1, 2, 5, 6, 8} and d = 9, there are two solutions: {1, 2, 6} and {1,
8}.
▪ It is convenient to sort the set’s elements in increasing order. So, we will assume
that
a1< a2 < . . . < an.
▪ The state-space tree can be constructed as a binary tree like that in Figure shown
below for the instance A = {3, 5, 6, 7} and d = 15.
▪ The number inside a node is the sum of the elements already included in the subsets
represented by the node. The inequality below a leaf indicates the reason for its
termination.
▪ Example: Apply backtracking to solve the following instance of the subset sum
problem:
A = {1, 3, 4, 5} and d = 11