Hello, how are you ? Today I shall discuss about binary search algorithm. First of all we know to need why we will use binary search algorithm ? We can use linear search algorithm for searching element in list, but why we will use this ? Because each time we must remember the time complexity of this program. The time complexity of linear search is O(n) where time complexity of binary search is O(log(n)). We will see that next.
Note: Binary search works on only sorted array.
We will discuss operation, At first you consider a list or array which has some integers type value and you declare three variables left , right and middle. left variable hold first index of this array which is 0, that means 0 is stored in the left variable. right variable holds the last index of this array, but how can we know the index of last variable? first, you will find the size of this array then to subtract 1 from this size, only then you will get the index of last element. Our main target find the search element, we can follow this below process
#include<stdio.h>
int main()
{
int a[]={1,2,3,4,5,65,57,87};
int item=87;
int left,right,middle;
left=0;
right=7;
while(left<=right){
middle=(left+right)/2;
if(a[middle]==item){
printf("Item found at index: %d\n",middle);
return 0;
}else if(a[middle]<item){
left=middle+1;
}else{
right=middle -1;
}
}
printf("Item is not found \n");
return 0;
}

Post a Comment