Implementation of binary search.
Source Code:
#include<stdio.h>
int main(){
int ary[20], n, i, j, searchElement;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&ary[i]);
printf("Enter search element:");
scanf("%d",&searchElement);
i = 0;
j = n-1;
while(i<=j){
if(ary[(i+j)/2]==searchElement){
printf("Element found at %d position.",(i+j)/2);
break;
} else if(ary[(i+j)/2]<searchElement){
i = (i+j)/2+1;
}else{
j = (i+j)/2-1;
}
}
if(i>j){
printf("Element not found.");
}
return 0;
}
int main(){
int ary[20], n, i, j, searchElement;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&ary[i]);
printf("Enter search element:");
scanf("%d",&searchElement);
i = 0;
j = n-1;
while(i<=j){
if(ary[(i+j)/2]==searchElement){
printf("Element found at %d position.",(i+j)/2);
break;
} else if(ary[(i+j)/2]<searchElement){
i = (i+j)/2+1;
}else{
j = (i+j)/2-1;
}
}
if(i>j){
printf("Element not found.");
}
return 0;
}
Enter size of array:5
Enter 5 elements:
9 6 8 2 5
Enter search element:6
Element found at 1 position.
Enter 5 elements:
9 6 8 2 5
Enter search element:6
Element found at 1 position.