You are on page 1of 7

Binary Search

Dr. Beulah Christudas


Assistant Professor, KITS
Linear Search vs Binary Search

☉ Linear Search
๏ Complexity : O(n)
๏ Not efficient for large arrays
☉ Binary Search
๏ Also known as half-interval search, logarithmic
search or binary chop.
๏ Works on a sorted array.
Example
☉ Given array : [23, 65, 72, 45, 89, 12, 52]
☉ Assume s = 45
☉ Sort the array : [12, 23, 45, 52, 65, 72, 89]
☉ Let low = 0 and high = n-1 = 6; mid = (0+6)/2 = 3
☉ Initially the middle element is a[3] = 52
☉ Since 45<52, we move high to mid-1 = 2
☉ Now, we focus on [ 12, 23, 45]
☉ Now, low = 0, high = 2, mid = 1
☉ 45 is now > a[mid] = 23, so we move low to mid+1 = 2
☉ Now, low = 2, high = 2, mid = 2
☉ So we focus on only one element a[2] = 45
☉ Now s = a[mid] => Element found.
Source Code - sort
void sort(int a[10], int n) if (a[i]>a[j])
{ {
int i,j,t; t=a[i];
for (i=0;i<n;i++) a[i]=a[j];
for (j=i+1;j<n;j++) a[j]=t;
}
}
search
int bsearch(int a[],int n, int s) if (s==a[mid])
{ return 1;
int low=0,high=n-1, mid; else if (s<a[mid])
int i; high=mid-1;
while (low<=high) else if (s>a[mid])
{ low=mid+1; }
mid=(low+high)/2; return 0; }
Thank you!

You might also like