└── binary search /binary search: -------------------------------------------------------------------------------- 1 | // C++ program to implement iterative Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // An iterative binary search function. 6 | int binarySearch(int arr[], int l, int r, int x) 7 | { 8 | while (l <= r) { 9 | int m = l + (r - l) / 2; 10 | 11 | // Check if x is present at mid 12 | if (arr[m] == x) 13 | return m; 14 | 15 | // If x greater, ignore left half 16 | if (arr[m] < x) 17 | l = m + 1; 18 | 19 | // If x is smaller, ignore right half 20 | else 21 | r = m - 1; 22 | } 23 | 24 | // If we reach here, then element was not present 25 | return -1; 26 | } 27 | 28 | // Driver code 29 | int main(void) 30 | { 31 | int arr[] = { 2, 3, 4, 10, 40 }; 32 | int x = 10; 33 | int n = sizeof(arr) / sizeof(arr[0]); 34 | int result = binarySearch(arr, 0, n - 1, x); 35 | (result == -1) 36 | ? cout << "Element is not present in array" 37 | : cout << "Element is present at index " << result; 38 | return 0; 39 | } 40 | --------------------------------------------------------------------------------