From d177b2e270b78b9d600e18dba9cb0839a5cd5bb2 Mon Sep 17 00:00:00 2001 From: CODESTIEN <32845547+Tarunyo@users.noreply.github.com> Date: Tue, 2 Oct 2018 15:24:52 +0530 Subject: [PATCH] made changes this change is more better than the original code(it is simple ,easy and basic code for binary search in c++) --- searches/binary_search.cpp | 93 +++++++++++++++++++++----------------- 1 file changed, 52 insertions(+), 41 deletions(-) diff --git a/searches/binary_search.cpp b/searches/binary_search.cpp index fae0d170..dbd821c9 100644 --- a/searches/binary_search.cpp +++ b/searches/binary_search.cpp @@ -1,47 +1,58 @@ -// Binary Search implemented in C++ -// Carlos Abraham Hernandez -// algorithms.abranhe.com/searches/binary-search -// repl.it/@abranhe/Binary-Search +#include +#include -#include -using namespace std; - -int binary_search(int a[],int l,int r,int key) +void bsearch(int ar[], int size, int item) { - while(l<=r) - { - int m = l + (r-l) / 2; - - if(key == a[m]) - return m; - else if(key < a[m]) - r = m-1; - else - l = m+1; - } - return -1; +int mid,beg,last,temp,pos; +char flag='n'; +beg=0; +last=(size-1); +while(beg<=last) +{ +mid=(beg+last)/2; +if(ar[mid]==item) +{ +flag='y'; +pos=mid+1; +break; +} +else if(item>ar[mid]) +beg=mid+1; +else +last=mid-1; +} +if(flag=='y'){ +cout<<"\n\nElement found at "<>size; +if(size<50) { - int n, key; - cout << "Enter size of array: "; - cin >> n; - cout << "Enter array elements: "; - int a[n]; - - for (int i = 0; i < n; ++i) - { - cin>>a[i]; - } - cout << "Enter search key: "; - cin>>key; - - int res = binary_search(a, 0, n-1, key); - - if(res != -1) - cout<< key << " found at index " << res << endl; - else - cout << key << " not found" << endl; - return 0; +cout<<"\n\nEnter elements:\n"; +for(int i=0;i>ar[i]; +} +cout<<"\n\nEnter element to be search: "; +cin>>item; +bsearch(ar,size,item); +getch(); +} +else +{ +cout<<"\n\nWrong array size entered. Program terminating..."; +getch(); +} } +