Binary search tree: find: Difference between revisions

From Algowiki
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
[[Category:Binary_Search_Tree]]
[[Category:Binary_Search_Tree]]
[[Category:Algorithm]]
[[Category:Algorithm]]
<div class="plainlinks" style="float:right;margin:0 0 5px 5px; border:1px solid #AAAAAA; width:auto; padding:1em; margin: 0px 0px 1em 1em;">
<div style="font-size: 1.8em;font-weight:bold;text-align: center;margin:0.2em 0 1em 0">Binary Search Tree</div>
<div style="font-size: 1.2em; margin:.5em 0 1em 0; text-align:center">[[Sorted sequence]]</div>
<div style="font-size: 1.2em; margin:.5em 0 .5em 0;text-align:center">[[File:olw_logo1.png|20px]][https://openlearnware.tu-darmstadt.de/#!/resource/binary-search-tree-1938 Openlearnware]<br>See Chapter 2,3</div>
</div>
== General Information ==
== General Information ==



Revision as of 09:25, 1 October 2014

General Information

Algorithmic Problem: Sorted Sequence:find

Type of algorithm: loop

Auxiliary data: A pointer p of type "pointer to binary search tree node of type [math]\displaystyle{ \kappa }[/math]".

Abstract view

Invariant: After [math]\displaystyle{ i\geq 0 }[/math] Iterations.

  1. The pointer p points to a tree node v on height level i (or is void).
  2. The key K is in the range of v.

Variant: i is increased by 1.

Break condition: Either it is [math]\displaystyle{ p = void }[/math] or, otherwise, [math]\displaystyle{ p.key = K }[/math].

Induction basis

Abstract view: Set p:= root.

Implementation: Obvious

Proof: Nothing to show

Induction step

Abstract view: If p points to a node but not with key K, p descends in the appropriate direction, left or right.

Implementation:

  1. If [math]\displaystyle{ p = void }[/math], terminate the algorithm and return false.
  2. Otherwise, if [math]\displaystyle{ p.key = K }[/math], terminate the algorithm and return true.
  3. Otherwise:
    1. If [math]\displaystyle{ K \lt p.key }[/math], set [math]\displaystyle{ p := left }[/math].
    2. If [math]\displaystyle{ K \gt p.key }[/math], set [math]\displaystyle{ p := right }[/math].

Correctnes: Obvious.

Complexity

Statement: Linear in the length of the sequence in the worst case (more precisely, linear in the height of the tree).

Worst case binary search tree

Proof: Obvious.

Pseudocode

TREE-SEARCH (x, k)

if x= NIL or k = key[x]
then return x
if k < key[x]
then return TREE-SEARCH(left[x], k)
else return TREE-SEARCH(right[x], k)