1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
#if 1
int binSearch(const vector<int>& sorted, int target) {
int mid = sorted.size() / 2;
if (sorted.size() == 0)
return -1;
if (sorted[mid] == target)
return mid;
if (sorted.size() == 1)
return -1;
if (sorted[mid] > target)
return binSearch(vector<int>(sorted.begin(), sorted.begin() + mid), target);
else {
int x = binSearch(vector<int>(sorted.begin() + mid + 1, sorted.end()), target);
return x == -1 ? -1 : mid + x;
}
}
#else
int binSearch2(const vector<int>& sorted, int lo, int hi, int target) {
if (lo >= hi)
return -1;
int mid = lo + (hi - lo) / 2;
if (target == sorted[mid])
return mid;
else if (target < sorted[mid])
return binSearch2(sorted, lo, mid, target);
else
return binSearch2(sorted, mid + 1, hi, target);
}
int binSearch(const vector<int>& sorted, int target) {
binSearch2(sorted, 0, sorted.size(), target);
}
#endif
int main(int argc, char **argv) {
int key = 9;
if (argc == 2)
key = atoi(argv[1]);
vector<int> checkVal = { 1,2,3,4,5,6,7,8,10,11,12,13,14,15,16 };
int index = binSearch(checkVal, key);
if (index == -1)
cout << "binSearch can't find " << key << "\n";
else
cout << "binSearch found " << key << " at position " << index << "\n";
}
|