Linear and Binary Search
Linear and Binary Search
Linear and Binary Search
Sequential (linear) and binary search are two methods for finding a given element in a list.
Sequential search checks every elements of the list, one at a time and in sequence, until the
desired element is found or the list ends. Whereas, binary search operates on a sorted list and
finds the given element by comparing it with the middle element of the list. The comparison
determines whether the middle element is equal to the given element, less than the input or
greater.
/* Apply sequential search to iterable collection (of type T) for the given item. */
public static <T> boolean sequentialSearch (Iterable<T> collection, T searchKey)
{
Iterator<T> iter = collection.iterator( );
while (iter.hasNext())
{
if (iter.next( ).equals(searchKey))
{
return true;
}
}
return false;
}
}
/* Uses first definition of sequentialSearch and search through the indexed list */
System.out.println("Search key " + searchKey + " is found? " +
SequentialSearch.sequentialSearch (arr, searchKey));
OUTPUT
======
Search key 5 is found? true
Search key 5 is found? True
Both methods of SequentialSearch are static, therefore it is not needed to create an object of
class SequentialSearch in order to call sequentialSearchmethods. Both methods operate on type
parameter T that specifies the elements in the collection; T must provide a valid equals(Object
o) method.
import java.util.*;
class BinarySearch
{
/* Apply binary search to search the sorted list (of type T) for the given item. */
public static <T extends Comparable<T>> boolean binarySearch (T[] list, T searchKey)
{
// null is never included in the list
if (searchKey == null)
{
return false;
}
int low = 0, high = list.length - 1;
while (low <= high)
{
int mid = (low + high)/2;
int rc = searchKey.compareTo(list[mid]);
if (rc < 0)
{
// searchKey is less than list[i]
high = mid - 1;
}
else if (rc > 0)
{
// searchKey is greater than list[i]
low = mid + 1;
}
else
{
// found the item.
return true;
}
}
return false;
}
}
Above binary search implementation in Java uses three important variables: low,high,
and mid. low is the lowest index of the current sub-array being searched,high is the upper index
of the same sub-array, and mid is the midpoint of the sub-array.