Online Compiler - CodeBook Solution
</>
CodeBook
.
Home
Services
DSA Practice
Compiler
Blog
Contact
ā°
ā” CodeBook Compiler
ā Back to DSA
C++ (GCC)
Python 3
Java
JavaScript (Node)
C (GCC)
Go
Ruby
Clear
ā¶ Run Code
š Code Editor
// Binary Search // Given a sorted array, find the target element. #include <bits/stdc++.h> using namespace std; class Solution { public: int search(vector<int>& nums, int target) { int lo = 0, hi = nums.size() - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; } }; int main() { Solution sol; vector<int> nums = {-1, 0, 3, 5, 9, 12}; cout << sol.search(nums, 9) << endl; // Output: 4 cout << sol.search(nums, 2) << endl; // Output: -1 return 0; }
š Output
// Your output will appear here...
š„ Standard Input (optional)