fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm> // For sort
  4. using namespace std;
  5.  
  6. int binarySearch(vector<int> &arr, int target) {
  7. int low = 0;
  8. int high = arr.size() - 1;
  9.  
  10. while (low <= high) {
  11. int mid = low + (high - low) / 2;
  12.  
  13. // Print current low, mid, high
  14. cout << "Low: " << low << ", Mid: " << mid << ", High: " << high << endl;
  15.  
  16. if (arr[mid] == target) {
  17. return mid;
  18. }
  19. else if (arr[mid] < target) {
  20. low = mid + 1;
  21. }
  22. else {
  23. high = mid - 1;
  24. }
  25. }
  26.  
  27. return -1; // Not found
  28. }
  29.  
  30. int main() {
  31. int n, target;
  32. cout << "Enter the number of elements in the array: ";
  33. cin >> n;
  34.  
  35. vector<int> arr(n);
  36. cout << "Enter " << n << " integers (sorted or unsorted): ";
  37. for (int i = 0; i < n; ++i) {
  38. cin >> arr[i];
  39. }
  40.  
  41. // Optional: sort the array if not sorted
  42. sort(arr.begin(), arr.end());
  43.  
  44. cout << "Enter the target value to search: ";
  45. cin >> target;
  46.  
  47. int result = binarySearch(arr, target);
  48.  
  49. if (result != -1) {
  50. cout << "Element found at index (in sorted array): " << result << endl;
  51. }
  52. else {
  53. cout << "Element not found in the array." << endl;
  54. }
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5312KB
stdin
45
stdout
Enter the number of elements in the array: Enter 45 integers (sorted or unsorted): Enter the target value to search: Low: 0, Mid: 22, High: 44
Low: 23, Mid: 33, High: 44
Low: 34, Mid: 39, High: 44
Low: 40, Mid: 42, High: 44
Low: 43, Mid: 43, High: 44
Low: 44, Mid: 44, High: 44
Element not found in the array.