Last active
May 31, 2020 09:49
-
-
Save misterpoloy/e802e30fd51844258836e0623d8886b6 to your computer and use it in GitHub Desktop.
Binary Search in cpp iterative and recursive
This file contains hidden or 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
#include <vector> | |
using namespace std; | |
class BST { | |
public: | |
int value; | |
BST *left; | |
BST *right; | |
BST(int val); | |
}; | |
vector<int> inOrderTraverse(BST *tree, vector<int> array = {}) { | |
if (tree->left != NULL) { | |
array = inOrderTraverse(tree->left, array); | |
} | |
array.push_back(tree->value); | |
if (tree->right != NULL) { | |
array = inOrderTraverse(tree->right, array); | |
} | |
return array; | |
} | |
vector<int> preOrderTraverse(BST *tree, vector<int> array) { | |
array.push_back(tree->value); | |
if (tree->left != NULL) { | |
array = preOrderTraverse(tree->left, array); | |
} | |
if (tree->right != NULL) { | |
array = preOrderTraverse(tree->right, array); | |
} | |
return array; | |
} | |
vector<int> postOrderTraverse(BST *tree, vector<int> array) { | |
if (tree->left != NULL) { | |
array = postOrderTraverse(tree->left, array); | |
} | |
if (tree->right != NULL) { | |
array = postOrderTraverse(tree->right, array); | |
} | |
array.push_back(tree->value); | |
return array; | |
} |
This file contains hidden or 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
// https://www.youtube.com/watch?v=-bQ4UzUmWe8&list=PL2_aWCzGMAwL3ldWlrii6YeLszojgH77j&index=3 | |
#include <iostream> | |
int BinarySearch(int* A, int n, int target) { | |
int low, high; | |
low = 0; | |
high = n - 1; | |
while (low <= high) { | |
int mid = low + (low + high) / 2; // low + (high -low) / 2 | |
if (target == A[mid]) return mid; | |
else if (A[mid] > target) { | |
high = mid - 1; | |
} | |
else if (A[mid] < target) { | |
low = mid + 1; | |
}; | |
} | |
return -1; | |
} | |
int BinarySearchRecursive(int* A, int low, int high, int target) { | |
int mid = low + (high - low) / 2; | |
if (low > high) return -1; | |
if (target == A[mid]) return mid; | |
else if (target > A[mid]) return BinarySearchRecursive(A, mid + 1, high, target); | |
else return BinarySearchRecursive(A, low, mid - 1, target); | |
} | |
int main() { | |
int A[] = { 1, 2, 3, 4, 5, 6, 7 }; | |
int n = sizeof(A) / sizeof(A[0]); | |
int target = 7; | |
int result = BinarySearch(A, n, target); | |
int recursiveResult = BinarySearchRecursive(A, 0, n - 1, target); | |
std::cout << target << (recursiveResult != -1 ? " exist" : " does not exist") << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment