Algorithm-Renewed
This commit is contained in:
36
Algorithm/Divide&Conquer/BinarySearch.cpp
Normal file
36
Algorithm/Divide&Conquer/BinarySearch.cpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
using namespace std;
|
||||
|
||||
auto search(vector<int>& arr, int start, int end, int target) -> int{
|
||||
if(start >= end) return -1;
|
||||
|
||||
int mid = (start + end) / 2;
|
||||
|
||||
if(target == arr[mid]) return mid;
|
||||
else if(target < arr[mid])
|
||||
search(arr, start, mid, target);
|
||||
else if(target > arr[mid])
|
||||
search(arr, mid + 1, end, target);
|
||||
|
||||
}
|
||||
|
||||
int main(){
|
||||
vector<int> arr;
|
||||
int n;
|
||||
cin >> n;
|
||||
arr.resize(n);
|
||||
for(int i = 0; i < n; i++){
|
||||
cin >> arr[i];
|
||||
}
|
||||
sort(arr.begin(), arr.end());
|
||||
int t;
|
||||
cin >> t;
|
||||
int pos = search(arr, 0, arr.size() - 1, t);
|
||||
if(pos != -1)
|
||||
cout << "Pos: " << pos + 1 << ", Num: " << arr[pos] << endl;
|
||||
else
|
||||
cout << "Not Found" << endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user