Created
November 21, 2018 17:24
-
-
Save manojnaidu619/108a949d437dd3ca91807baa45e871b4 to your computer and use it in GitHub Desktop.
Binary search in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
int main(){ | |
int n, a[100], search; | |
printf("Enter size of array\n"); | |
scanf("%d",&n); | |
printf("enter %d elements\n",n); | |
for(int i=0;i<n;i++){ | |
scanf("%d",&a[i]); | |
} | |
printf("Enter search element:\n"); | |
scanf("%d",&search); | |
int first=0, last=n-1, mid=(first+last)/2; | |
while(first <= last){ | |
if(a[mid] == search){ | |
printf("Element found at position %d!!\n",mid+1); | |
break; | |
} | |
else if(a[mid] < search){ | |
first = mid+1; | |
} | |
else{ | |
last = mid-1; | |
} | |
mid = (first+last)/2; | |
} | |
if(first>last){ | |
printf("Not found!!\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment