By
Dr. Yasser Abdelhamid
y Abdelhamid
Searching algorithms Cont.
Binary Search
Iterative
Recursive
Dr. Yasser Abdelhamid
y Abdelhamid
Binary search algorithm is an efficient
algorithm that run in the O(log2n).
It uses the divide and conquer strategy for
solving the search problem.
It is only applicable to sorted lists.
Dr. Yasser Abdelhamid
Abdelhamid
y
Dr. Yasser Abdelhamid
y Abdelhamid
If list is empty, search is
complete with fail.
Compare key to the
middle element of list
If key < middle element
of list, search is
restricted to first half of
the list
If key > middle element
of list, search second
half of the list
If key = middle element,
search is complete with
success.
Dr. Yasser Abdelhamid
y Abdelhamid
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
Dr. Yasser Abdelhamid
}
}
y Abdelhamid
A list of 11 elements takes 4 tries
A list of 32 elements takes 5 tries
A list of 250 elements takes 8 tries
A list of 512 elements takes 9 tries
32 = 25 log2(32) = 5
512 = 29 log2(512) = 9
8 < 11 < 16 23 < 11 < 24
128 < 250 < 256 27 < 250 < 28
So for a list of n, number of comparisons
is in O(log2n)
Dr. Yasser Abdelhamid
y Abdelhamid
public static int binarySearch(int [ ] list, int first, int, last, int key)
{
if(first > last) return FALSE; c1
mid = (first + last) / 2; c2
c3
if(key==list[mid]) return TRUE;
if(key<list[mid])
T(n/2)
return binarySearch(list, first, mid-1, key);
if(key>list[mid])
return binarySearch(list, mid+1, last, key); T(n/2)
Dr. Yasser Abdelhamid
Abdelhamid
y
Dr. Yasser Abdelhamid