fork download
  1. #include<stdio.h>
  2. int binary_search(int n,int a[],int key);
  3. int main(){
  4. int i, pos,n,key,a[100];
  5. printf("Enter number of elements . \n");
  6. scanf("%d",&n);
  7. printf("Enter %d integers : \n",n);
  8. for(i=0;i<n;i++){
  9. scanf("%d",&a[i]);
  10. }
  11. printf("Enter value to find : ");
  12. scanf("%d",&key);
  13. pos = binary_search(n,a,key);
  14. if(pos>=0){
  15. printf("\n%d is location of data in array. ",pos);
  16. }
  17. else{
  18. printf("%d is not present in list",key);
  19. }
  20. return 0;
  21. }
  22. int binary_search(int n,int a[], int key){
  23. int bottom = 0, mid;
  24. int top = n-1;
  25. while(bottom<=top){
  26. mid=(top+bottom)/2;
  27. if(key == a[mid]){
  28. return mid;
  29. }
  30. if(key<a[mid]){
  31. top = mid - 1;
  32. }
  33. else{
  34. bottom = mid + 1;
  35. }
  36. }
  37. return 0;
  38. }
Success #stdin #stdout 0s 5300KB
stdin
5
10 12 1 5 13 
1
stdout
Enter number of elements . 
Enter 5 integers : 
Enter value to find : 
2 is location of data in array.