Joshua Laurence F. Caro BSIT 2-3 N: Binary Search or Half-Interval Search
Joshua Laurence F. Caro BSIT 2-3 N: Binary Search or Half-Interval Search
Caro
BSIT 2-3
n
BINARY SEARCH OR HALF-INTERVAL SEARCH ALGORITHM
It finds the position of a specified input value (the search "key") within an array
sorted by key value.[1][2] For binary search, the array should be arranged in ascending or
descending order. In each step, the algorithm compares the search key value with the key
value of the middle element of the array. If the keys match, then a matching element has
been found and its index, or position, is returned. Otherwise, if the search key is less than
the middle element's key, then the algorithm repeats its action on the sub-array to the left of
the middle element or, if the search key is greater, on the sub-array to the right. If the
remaining array to be searched is empty, then the key cannot be found in the array and a
special "not found" indication is returned.
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
break;
}
else if(m<a[mid]){
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
return 0;
}
#include<stdio.h>
int main(){
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
return 0;
}