J.E.D.I
implementation implies a larger space overhead for pointers but insertions and deletions can be performed immediately.
8.4.3.2 Binary Search
Binary search begins with an interval covering the whole table, that is the middle value. If the search value is less than the item in the middle of the interval, the interval is
narrowed down to the lower half. Otherwise, it is narrowed down to the upper half. This process of reducing the search size by half is repeatedly performed until the value is
found or the interval is empty. The algorithm for the binary search makes use of the following relations in searching for the key K:
• K = K
i
: stop, the desired record is found • K K
i
: search the lower half - records with keys K
1
to K
i-1
• K K
i
: search the upper half - records with keys K
i+1
to K
n
where i is initially the middle index value. The Algorithm
Returns the index of key k if found, otherwise -1 int binarySearchint k, Table t{
int lower = 0; int upper = t.size - 1;
int middle;
while lower upper{ get middle
middle = int Math.floorlower + upper 2; successful search
if k == t.key[middle] return middle; discard lower half
else if k t.key[middle] lower = middle + 1; discard upper half
else upper = upper - 1; }
return-1; unsuccessful search }
For example, search for the key k=34567:
1 2
3 4
5 6
12345 23456
34567 45678
56789 67890
78901 lower = 0, upper = 6, middle = 3: k k
middle
45678 lower = 0, upper = 2, middle = 1: k k
middle
23456
Data Structures 166
J.E.D.I
lower = 2, upper = 2, middle = 2: k = k
middle
34567 == successful search Since the search area is reduced logarithmically, i.e., halved each time the size is
reduced, the time complexity of the algorithm is Olog
2
n. The algorithm may be used if the table uses indexed sequential organization. However, it can only be used with
ordered tables stored as an array.
8.4.3.3 Multiplicative Binary Search
Multiplicative binary search is similar to the previous algorithm but avoids the division needed to find the middle key. To do that, there is a need to rearrange the records in
the table:
1. Assign keys K
1
K
2
K
3
… K
n
to the nodes of a complete binary tree in inorder sequence
2. Arrange the records in the table according to the corresponding level-order sequence in the binary tree.
The Search Algorithm The comparison begins at the root of the binary tree, j=0, which is the middle key in the
original table. Accepts a set of keys represented as a complete binary tree
int multiplicativeBinarySearchint k, int key[]{ int i = 0;
while i key.length{ if k == key[i] return i; successful search
else if k key[i] i = 2 i + 1; go left else i = 2 i + 2; go right
} return -1; unsuccessful search
} Since computation for the middle element is eliminated, multiplicative binary search is
faster than the traditional binary search. However, there is a need to rearrange the given set of keys before the algorithm can be applied.
8.4.3.4 Fibonacci Search