|
|
|
Value Lookup(Key k)
{
e = BinarySearch(k); // Binary search works on sorted arrays !!!
if ( e.key == k )
{
return e.value; // Return value
}
else
{
return null; // Not found
}
}
|
Insert(Key k, Value v)
{
Find first element e such that: e.key ≥ k (with a modified binary search)
// ........... e .........
// key < k | |
// +-----------+
// key >= k
if ( e.key == k )
e.value = v; // Replace value
else
{
for ( j = NItems; j >= index(e)+1; j-- )
{
bucket[j] = bucket[j-1]; // Make room for new entry
}
bucket[ index(e) ] = (k, v);
NItems++;
}
}
|
Delete(Key k)
{
e = BinarySearch(k); // Binary search works on sorted arrays !!!
if ( e == null )
{
return; // Not found... nothing to delete
}
else
{
for ( j = index(e); j < NItems-1; j++ )
{
bucket[j] = bucket[j+1]; // Copy array down...
}
NItems--;
}
}
|
|
|
Modified Binary Search:
public static int BinSearch(MyEntry[] Bucket, int N, int k)
{
int low, high, mid;
low = 0; // low end
high = N-1; // high end
mid = (high + low)/2;
/* ====================================================
This is the ordinary binary search algorithm
==================================================== */
while ( low <= high )
{
mid = (high + low)/2; // Middle element
if ( Bucket[mid].key == k )
{
return( mid ); // found
}
if ( k < Bucket[mid].key )
{
high = mid - 1; // Search lower half
}
else
{
low = mid + 1; // Search upper half
}
}
/* ==============================================================
When we arrive here, we have:
high < low
In any case, we are NEAR the key k
=============================================================== */
if ( high >= 0 && k <= Bucket[high].key )
return high;
if ( low < N && k <= Bucket[low].key )
return low;
return N; // Exceeded !
}
|
How to run the program:
|
Sample output:
0:(4,a) 1:(7,b) 2:(9,c) 3:(14,d) 4:(18,e) 5:(23,f) 6:(29,g) 7:(39,g) BinSearch(2) = 0 BinSearch(4) = 0 BinSearch(5) = 1 BinSearch(7) = 1 BinSearch(8) = 2 BinSearch(9) = 2 BinSearch(13) = 3 BinSearch(14) = 3 BinSearch(16) = 4 BinSearch(18) = 4 BinSearch(20) = 5 BinSearch(23) = 5 BinSearch(26) = 6 BinSearch(29) = 6 BinSearch(33) = 7 BinSearch(39) = 7 BinSearch(93) = 8 |
How to do it:
|
We will move on to something more interesting....