Skip to content

Commit

Permalink
added binarySearch.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
jenyyy4 authored and x0lg0n committed Oct 30, 2024
1 parent 0f48885 commit 7f00108
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions C++/binarySearch.cpp
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;
}

0 comments on commit 7f00108

Please sign in to comment.