mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
Create Binary search
This commit is contained in:
parent
e5dad3fa8d
commit
fd9236245c
29
searching/Binary search
Normal file
29
searching/Binary search
Normal file
@ -0,0 +1,29 @@
|
||||
#include <stdio.h>
|
||||
int main()
|
||||
{
|
||||
int i, low, high, mid, n, key, array[100];
|
||||
printf("Enter number of elementsn");
|
||||
scanf("%d",&n);
|
||||
printf("Enter %d integersn", n);
|
||||
for(i = 0; i < n; i++)
|
||||
scanf("%d",&array[i]);
|
||||
printf("Enter value to findn");
|
||||
scanf("%d", &key);
|
||||
low = 0;
|
||||
high = n - 1;
|
||||
mid = (low+high)/2;
|
||||
while (low <= high) {
|
||||
if(array[mid] < key)
|
||||
low = mid + 1;
|
||||
else if (array[mid] == key) {
|
||||
printf("%d found at location %d.n", key, mid+1);
|
||||
break;
|
||||
}
|
||||
else
|
||||
high = mid - 1;
|
||||
mid = (low + high)/2;
|
||||
}
|
||||
if(low > high)
|
||||
printf("Not found! %d isn't present in the list.n", key);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user