kucheasysa

binary

Jun 6th, 2023
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. int size, i, key, low, high, mid, found = 0;
  5.  
  6. printf("Enter the size of the array: ");
  7. scanf("%d", &size);
  8.  
  9. int arr[size];
  10.  
  11. printf("Enter the elements of the array in ascending order:\n");
  12. for (i = 0; i < size; i++) {
  13. scanf("%d", &arr[i]);
  14. }
  15.  
  16. printf("Enter the element to search: ");
  17. scanf("%d", &key);
  18.  
  19. low = 0;
  20. high = size - 1;
  21.  
  22. while (low <= high) {
  23. mid = (low + high) / 2;
  24.  
  25. if (arr[mid] == key) {
  26. found = 1;
  27. break;
  28. } else if (arr[mid] < key) {
  29. low = mid + 1;
  30. } else {
  31. high = mid - 1;
  32. }
  33. }
  34.  
  35. if (found) {
  36. printf("Element %d found at index %d\n", key, mid);
  37. } else {
  38. printf("Element %d not found in the array\n", key);
  39. }
  40.  
  41. return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment