diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 20:52:41 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 20:52:41 +0100 |
commit | 36260c39bee50e6160c99e240fcad63402e39346 (patch) | |
tree | 2cdccd7dd0ed7ca9abcf22eb296771033a630d52 /01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search | |
parent | 87ed554add4b7ac41499be9187c8da7b0365ca13 (diff) | |
download | coursera-36260c39bee50e6160c99e240fcad63402e39346.zip coursera-36260c39bee50e6160c99e240fcad63402e39346.tar.gz |
Algorithms : complete 01-algorithmic_toolbox 03-divide_and_conquer
Diffstat (limited to '01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search')
-rw-r--r-- | 01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp | 17 |
1 files changed, 12 insertions, 5 deletions
diff --git a/01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp b/01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp index c93e2cf..40f8f01 100644 --- a/01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp +++ b/01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp @@ -4,9 +4,16 @@ using std::vector; -int binary_search(const vector<int> &a, int x) { - int left = 0, right = (int)a.size(); - //write your code here +int binary_search(const vector<int> &a, int x) +{ + int left = 0, right = (int) a.size(); + while (left <= right) { + int mid = (left + right) / 2; + if (a[mid] == x) return mid; + if (a[mid] < x) left = (mid + 1); + else right = (mid - 1); + } + return -1; } int linear_search(const vector<int> &a, int x) { @@ -30,7 +37,7 @@ int main() { std::cin >> b[i]; } for (int i = 0; i < m; ++i) { - //replace with the call to binary_search when implemented - std::cout << linear_search(a, b[i]) << ' '; + std::cout << binary_search(a, b[i]) << ' '; } + std::cout << '\n'; } |