diff --git a/Algorithms/binary_search.cpp b/Algorithms/binary_search.cpp new file mode 100644 index 0000000..f29f5cb --- /dev/null +++ b/Algorithms/binary_search.cpp @@ -0,0 +1,42 @@ +// C program to implement recursive Binary Search +#include + +// A recursive binary search function. It returns +// location of x in given array arr[l..r] is present, +// otherwise -1 +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + + // If the element is present at the middle + // itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not + // present in array + return -1; +} + +int main(void) +{ + int arr[] = { 2, 3, 4, 10, 40 }; + int n = sizeof(arr) / sizeof(arr[0]); + int x = 10; + int result = binarySearch(arr, 0, n - 1, x); + (result == -1) ? printf("Element is not present in array") + : printf("Element is present at index %d", + result); + return 0; +} diff --git a/Algorithms/minimax.cpp b/Algorithms/minimax.cpp new file mode 100644 index 0000000..5c484dd --- /dev/null +++ b/Algorithms/minimax.cpp @@ -0,0 +1,53 @@ +// A simple C++ program to find +// maximum score that +// maximizing player can get. +#include +using namespace std; + +// Returns the optimal value a maximizer can obtain. +// depth is current depth in game tree. +// nodeIndex is index of current node in scores[]. +// isMax is true if current move is +// of maximizer, else false +// scores[] stores leaves of Game tree. +// h is maximum height of Game tree +int minimax(int depth, int nodeIndex, bool isMax, + int scores[], int h) +{ + // Terminating condition. i.e + // leaf node is reached + if (depth == h) + return scores[nodeIndex]; + + // If current move is maximizer, + // find the maximum attainable + // value + if (isMax) + return max(minimax(depth+1, nodeIndex*2, false, scores, h), + minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); + + // Else (If current move is Minimizer), find the minimum + // attainable value + else + return min(minimax(depth+1, nodeIndex*2, true, scores, h), + minimax(depth+1, nodeIndex*2 + 1, true, scores, h)); +} + +// A utility function to find Log n in base 2 +int log2(int n) +{ + return (n==1)? 0 : 1 + log2(n/2); +} + +// Driver code +int main() +{ + // The number of elements in scores must be + // a power of 2. + int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; + int n = sizeof(scores)/sizeof(scores[0]); + int h = log2(n); + int res = minimax(0, 0, true, scores, h); + cout << "The optimal value is : " << res << endl; + return 0; +} \ No newline at end of file