-
Notifications
You must be signed in to change notification settings - Fork 101
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Binary Search Algorithm (#258)
- Loading branch information
1 parent
bf3ac6f
commit 168983e
Showing
1 changed file
with
49 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,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; | ||
} |