Advertisement
shawonrog

binary search1

Jun 3rd, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int j, low, high, mid, n, search, array[50];
  6.  
  7. printf("Enter number of elements\n");
  8. scanf("%d",&n);
  9.  
  10. printf("Enter %d integers\n", n);
  11.  
  12. for (j = 0; j < n; j++)
  13. scanf("%d",&array[j]);
  14.  
  15. printf("Enter value to find\n");
  16. scanf("%d", &search);
  17.  
  18. low = 0;
  19. high = n - 1;
  20. mid = (low+high)/2;
  21.  
  22. while (low <= high) {
  23. if (array[mid] < search)
  24. low = mid + 1;
  25. else if (array[mid] == search) {
  26. printf("%d found at location %d.\n", search, mid+1);
  27. break;
  28. }
  29. else
  30. high = mid - 1;
  31.  
  32. mid = (low + high)/2;
  33. }
  34. if (low > high)
  35. printf("Not found! %d isn't present in the list.\n", search);
  36.  
  37. return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement