-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
#include <iostream> | ||
#include <vector> | ||
|
||
int binarySearch(const std::vector<int>& arr, int target) { | ||
int left = 0; | ||
int right = arr.size() - 1; | ||
|
||
while (left <= right) { | ||
int mid = left + (right - left) / 2; | ||
if (arr[mid] == target) { | ||
return mid; | ||
} else if (arr[mid] < target) { | ||
left = mid + 1; | ||
} else { | ||
right = mid - 1; | ||
} | ||
} | ||
|
||
return -1; | ||
} | ||
|
||
int main() { | ||
std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; | ||
int target = 5; | ||
|
||
int result = binarySearch(arr, target); | ||
|
||
if (result != -1) { | ||
std::cout << "Element found at index " << result << std::endl; | ||
} else { | ||
std::cout << "Element not found" << std::endl; | ||
} | ||
|
||
return 0; | ||
} |