20.02.2021 Aufrufe

[Thomas_H._Cormen]_Algorithms_unlocked(BookZZ.org)

Sie wollen auch ein ePaper? Erhöhen Sie die Reichweite Ihrer Titel.

YUMPU macht aus Druck-PDFs automatisch weboptimierte ePaper, die Google liebt.

Chapter 3: Algorithms for Sorting and Searching 31

Termination: If x is not in the array, then eventually the procedure gets

to the point where p and r are equal. When that happens, step 2A

computes q to be the same as p and r. If step 2C sets r to q 1,

then at the start of the next iteration, r will equal p 1, sothatp

will be greater than r. If step 2D sets p to q C 1, then at the start

of the next iteration, p will equal r C 1, and again p will be greater

than r. Either way, the loop test in step 2 will come up false, and

the loop will terminate. Because p>r, the subarray AŒp : : r will

be empty, and so the value x cannot be present in it. Taking the

contrapositive of the loop invariant (see page 22) gives us that if x is

not present in the subarray AŒp : : r, then it is not present anywhere

in array A. Therefore, the procedure is correct in returning NOT-

FOUND in step 3.

We can also write binary search as a recursive procedure:

Procedure RECURSIVE-BINARY-SEARCH.A;p;r;x/

Inputs and Output: Inputs A and x are the same as LINEAR-SEARCH,

as is the output. The inputs p and r delineate the subarray AŒp : : r

under consideration.

1. If p>r, then return NOT-FOUND.

2. Otherwise (p r), do the following:

A. Set q to b.p C r/=2c.

B. If AŒq D x, then return q.

C. Otherwise (AŒq ¤ x), if AŒq > x, then return

RECURSIVE-BINARY-SEARCH.A;p;q 1; x/.

D. Otherwise (AŒq < x), return

RECURSIVE-BINARY-SEARCH.A; q C 1; r; x/.

The initial call is RECURSIVE-BINARY-SEARCH.A;1;n;x/.

Now let’s see how it is that binary search takes O.lg n/ time on an

n-element array. The key observation is that the size r p C 1 of the

subarray under consideration is approximately halved in each iteration

of the loop (or in each recursive call of the recursive version, but let’s

focus on the iterative version in BINARY-SEARCH). If you try all the

cases, you’ll find that if an iteration starts with a subarray of s elements,

the next iteration will have either bs=2c or s=2 1 elements, depending

on whether s is even or odd and whether AŒq is greater than or less

than x. We have already seen that once the subarray size gets down to 1,

Hurra! Ihre Datei wurde hochgeladen und ist bereit für die Veröffentlichung.

Erfolgreich gespeichert!

Leider ist etwas schief gelaufen!