Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- int recursion(int* a, int key, int l, int r) {
- int middle = (l + r) / 2;
- cout << "middle: " << middle << ", left: " << l << ", right: " << r << endl;
- if (a[middle] == key) return middle;
- if (l == middle || r == middle) return -1;
- if (key < a[middle]) return recursion(a, key, l, middle);
- if (key > a[middle]) return recursion(a, key, middle, r);
- }
- int iterative(int* a, int key, int l, int r) {
- int middle = (l + r) / 2;
- while (true) {
- cout << "middle: " << middle << ", left: " << l << ", right: " << r << endl;
- middle = (l + r) / 2;
- if (key < a[middle]) r = middle - 1;
- else if (key > a[middle]) l = middle + 1;
- else return middle;
- if (l > r) return -1;
- }
- }
- int main() {
- int a[19] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 };
- cout << "recursion => " << endl;
- cout << recursion(a, 3, 0, 18) << endl;
- cout << "iterative => " << endl;
- cout << iterative(a, 3, 0, 18) << endl;
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement