fork download
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int val[10] = {10,20,30,40,50,55,68,77,89,90};//Fig 3
  6. int beg = 0; //first index of array
  7. int end = 9; //end(last index of array) = n-1 where n is the size of array and is 10 in this case.
  8. int mid = (beg+end)/2; // finds middle index of array.
  9. int i;
  10. int element;
  11. //printf("enter the element you want search for");
  12. scanf("%d",&element);
  13. for(i=0;i<10;i++) //Fig 4
  14. {
  15. if(val[mid] == element) {
  16. break;
  17. }
  18. else if(val[mid] < element) {
  19. beg = mid +1;
  20. mid = (beg +end)/2;
  21. }
  22. else{
  23. end =mid -1;
  24. mid = (beg +end)/2;
  25. }
  26. }
  27. printf("Location of element is %d",mid);
  28. return 0;
  29. }
Success #stdin #stdout 0s 2296KB
stdin
68
stdout
Location of element is 6