Skip to content

Commit

Permalink
Added Binary Search Algorithm (#258)
Browse files Browse the repository at this point in the history
  • Loading branch information
VikrantKadam028 authored Oct 3, 2024
1 parent bf3ac6f commit 168983e
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions C++/BinarySearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int binarySearch(const 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() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;

vector<int> arr(n);
cout << "Enter " << n << " sorted elements (in ascending order):" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

int target;
cout << "Enter the target value to search for: ";
cin >> target;

int result = binarySearch(arr, target);
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}

return 0;
}

0 comments on commit 168983e

Please sign in to comment.