diff --git a/Binary_search/README.md b/Binary_search/README.md new file mode 100644 index 0000000..06ebb67 --- /dev/null +++ b/Binary_search/README.md @@ -0,0 +1,10 @@ +BINARY ALGORITHM +This algorithm help the user to search a particular element present in an array(using the index of element present in an array) +**How the Algorithm Works** +1. Find the middle element +2. If middle element equal to searched value algorithm stops: + otherwise there are two cases: + 2.1 search the value is less than that of the middle element.Here, + the algorithm go to the step 1 for the part of the array that before middle element + 2.2 search the value is greater than that of the middle element.And here, + the algorithm go to the step 1 for the part of the array that after middle element diff --git a/Binary_search/main.cpp b/Binary_search/main.cpp new file mode 100644 index 0000000..354ea15 --- /dev/null +++ b/Binary_search/main.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) + { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + return binarySearch(arr, mid + 1, r, x); + } + return -1; +} + +int main(void) +{ + int arr[] = { 24, 33, 4, 130, 41 }; + int x = 4; + int n = sizeof(arr) / sizeof(arr[0]); + int result = binarySearch(arr, 0, n - 1, x); + (result == -1) ? cout << "No such Element in array" + : cout << "Element is present at index " << result; + return 0; +} \ No newline at end of file