fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int binarySearch(int arr[], int size, int target) {
  5. int low = 0;
  6. int high = size - 1;
  7.  
  8. while (low <= high) {
  9. int mid = low + (high - low) / 2;
  10.  
  11. // Show current low, mid, and high
  12. cout << "Low: " << low << ", Mid: " << mid << ", High: " << high << endl;
  13.  
  14. if (arr[mid] == target) {
  15. return mid; // Target found
  16. }
  17. else if (arr[mid] < target) {
  18. low = mid + 1; // Search right half
  19. }
  20. else {
  21. high = mid - 1; // Search left half
  22. }
  23. }
  24.  
  25. return -1; // Target not found
  26. }
  27.  
  28. int main() {
  29. int arr[] = {2, 4, 7, 10, 15, 20, 25};
  30. int size = sizeof(arr) / sizeof(arr[0]);
  31. int target;
  32.  
  33. cout << "Enter the number to search: ";
  34. cin >> target;
  35.  
  36. int result = binarySearch(arr, size, target);
  37.  
  38. if (result != -1) {
  39. cout << "Element found at index: " << result << endl;
  40. }
  41. else {
  42. cout << "Element not found." << endl;
  43. }
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 5316KB
stdin
45
stdout
Enter the number to search: Low: 0, Mid: 3, High: 6
Low: 4, Mid: 5, High: 6
Low: 6, Mid: 6, High: 6
Element not found.