Binary Search Using Iteration
Binary Search Using Iteration
2. Compare the item with mid i.e. a[mid]= a[3] is not equal to 15
A[0] A[1] A[2] A[3] A[4] A[5] A[6]
3 10 15 20 35 40 60
0 1 2 3 4 5 6
3 10 15 20 35 40 60
0 1 2 3 4 5 6
Therefore, we take
beg = mid + 1 = 1+1 = 2
Since beg=end
mid=(beg+end)/2=(2+2)/2=2
#include<stdio.h>
int BSearch(int a[], int selement, int low, int high)
{
int mid ;
while (low <= high)
{
mid = low + (high - low) / 2;
if (a[mid] == selement)
return mid;
else if (a[mid] < selement)
low = mid + 1;
else
high = mid - 1;
}
return -99;
}
Cont.
int main(void)
{
int number;
int a[] = {2, 3, 4, 5, 6, 9, 11, 12, 23};
int status ;
int selement;
printf("\n Enter the element to be searched: ");
scanf("%d", &selement);
status = BSearch(a, selement, 0, number - 1);
if (status == -99)
printf("\n Element not found");
else
printf("Element is found at index %d", status);
return 0;
}
Binary Search using Recursion
#include <stdio.h>
int BSearch(int a[], int selement, int low, int high)
{
int mid;
if (high >= low)
{
mid = low + (high - low) / 2;
if ( a[mid] == selement )
return mid;
else if (a[mid] > selement) // Search the left portion
return BSearch(a, selement, low, mid - 1);
else // Search the right portion
return BSearch(a, selement, mid + 1, high);
}
return -99;
}
Cont.
int main()
{
int a[] = {2, 3, 4, 5, 6, 9, 11, 12, 23};
int low = 0;
int high = 8;
int element;
int status;
printf("\n Enter the element to be searched: ");
scanf("%d", &element);
status = BSearch(a, element, low, high );
if(status == -99)
printf("\n Element not found: ");
else
printf("\n The element %d is present at index no %d", element, s);
return 0;
}
Time Complexity of Binary Search
Best Case Time Complexity of Binary Search
• The average case arises when the target element is present in some
location other than the central index or extremities. The time
complexity depends on the number of comparisons to reach the
desired element.
• In the following iterations, the size of the sub array is reduced using
the result of the previous comparison.
Initial length of array = n
n
Iteration1 : Length of array
2
n
2 n
Iteration 2 : Length of array 2
2 2
n
Iteration k : Length of array
2k
Cont.
• Since the target element is present in the first or the last index,
i.e. there are log n comparisons in total.