Created
May 4, 2017 17:55
-
-
Save MarkSilverMedia/5ba02bd2c41ee008e5712e69672d9f98 to your computer and use it in GitHub Desktop.
binary search (need this for later)
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<iostream> | |
using namespace std; | |
bool bsearch(int AR[], int N, int VAL); | |
int main() | |
{ | |
int AR[100],n,val; // Array size will be declared by user, or I might change to vector if that'll work. | |
bool found; | |
cout<<"Enter number of elements you want to insert "; | |
cin>>n; | |
cout<<"Enter element in ascending order\n"; | |
for(int i=0;i<n;i++) // Will replace this loop with the random generation shit I've got already. | |
{ | |
cout<<"Enter element "<<i+1<<":"; | |
cin>>AR[i]; | |
} | |
cout<<"\nEnter the number you want to search "; | |
cin>>val; | |
found=bsearch(AR,n,val); // Literally the only line you'll need for the actual search. | |
if(found) | |
cout<<"\nItem found"; | |
else | |
cout<<"\nItem not found"; | |
return 0; | |
} | |
bool bsearch(int AR[], int N, int VAL) // The actual function, yo. | |
{ | |
int Mid,Lbound=0,Ubound=N-1; | |
while(Lbound<=Ubound) | |
{ | |
Mid=(Lbound+Ubound)/2; | |
if(VAL>AR[Mid]) | |
Lbound=Mid+1; | |
else if(VAL<AR[Mid]) | |
Ubound=Mid-1; | |
else | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment