From 7a8df4b93283b32636d8f1e4666ab2521712d1ab Mon Sep 17 00:00:00 2001 From: Vineet Kumar Diwakar <114769998+VINEET-KUMAR-DIWAKAR@users.noreply.github.com> Date: Thu, 5 Oct 2023 23:06:44 +0530 Subject: [PATCH] Update 0.cpp Binary Search Tree program . In this program input provide should be in ascending order. --- Upload Your Code/Binary Search Tree/0.cpp | 40 +++++++++++++++++++---- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/Upload Your Code/Binary Search Tree/0.cpp b/Upload Your Code/Binary Search Tree/0.cpp index a6ffd6f..46fa0de 100644 --- a/Upload Your Code/Binary Search Tree/0.cpp +++ b/Upload Your Code/Binary Search Tree/0.cpp @@ -1,12 +1,40 @@ #include -#include -#include - using namespace std; -int main() -{ +int binarySearch(int arr[], int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) + return mid; + + if (arr[mid] < target) + left = mid + 1; + else + right = mid - 1; + } + + return -1; +} + +int main() { + cout << "enter the size of array"; + int size; + cin>> size; + int arr[size]; + for (int i = 0; i < size; i++) { + cin >> arr[i]; + } + int target ; + cout << "enter the target value"<>target; + int n = sizeof(arr) / sizeof(arr[0]); + int result = binarySearch(arr, 0, n - 1, target); + if (result == -1) + cout << "Element not present in array" << endl; + else + cout << "Element found at index " << result << endl; return 0; -} \ No newline at end of file +}