Professional Documents
Culture Documents
Linear search
a
The simplest form of a search is the linear search. This technique is meant
for searching a particular item in an unsorted data set in a sequential manner
until the desired data item is found. Linear search is easy to write and
efficient for short lists, but inefficient for long ones. To find any element in
a long array (list), there are far more efficient methods, provided that the
array is sorted. A program for linear search is as follows.
OUTPUT
126 found in the list
Binary search
(b) Binary search is a simple method of accessing a particular item in a sorted
(ordered) data set. A search for a particular item with a certain key value
resembles the search for a name in telephone directory or a word in a dictionary.
The approximate middle item of the data set is located, and its key value is
examined. If its value is too high, then the key of the middle element of the first
half of the set is examined and procedure is repeated on the first half until the
required item is found. If the value is too low, then the key of the middle entry
of the second half of the data set is tried and the procedure is repeated on the
second half. This process continues until the desired key is found or search
interval becomes empty. The binary search algorithm is based on binary search
tree.
Program 1(b): Iterative Binary search
class BinarySearchDemo
{
static Object[] a = { "AP", "KA", "MH", "MP", "OR", "TN", "UP", "WB"};
static Object key = "UP";
public static void main(String args[])
{
if( binarySearch() )
System.out.println(key + " found in the list");
else
System.out.println(key + " not found in the list");
}
static boolean binarySearch()
{ int c, mid, low = 0, high = a.length-1;
while( low <= high)
{ mid = (low + high)/2; c = ((Comparable)key).compareTo(a[mid]);
if( c < 0) high = mid-1;
else if( c > 0) low = mid+1;
else return true;
} return false;
}
}
OUTPUT
UP found in the list
OUTPUT
UP found in the list