| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Outputting Binary search
I have a problem now..
i am doing binary search on a few inputs but i can't seem to make it output whether the number is found ot not. below is my code for it. #include <iostream> using namespace std; int binarysearch(int sortedarray[100], int first, int last, int key) { while (first <= last ) { int mid = ( first + last ) / 2; if (key> sortedarray[mid] ) first = mid + 1; else if (key < sortedarray[mid]) last = mid - 1; else return mid; } return - (first+1); } void main() { int nums, a[100], finds; cout<<"Please enter no. of inputs."; cin>> nums; for (int i=0; i<nums; i++) { cout<<"Please enter your inputs."; cin>>a[i]; } cout<<"enter the number you want to find."; cin>> finds; binarysearch(a,a[0],a[nums],finds); } if anyone could help. really thanks alot. |
|
#2
|
|||
|
|||
|
i need to put my cout statement somewhere but i can't seem to figure out where
|
|
#3
|
|||
|
|||
|
See the changes
Code:
#include <iostream>
using namespace std;
int binarysearch(int sortedarray[100], int first, int last, int key)
{
while (first <= last )
{
int mid = ( first + last ) / 2;
if (key> sortedarray[mid] )
first = mid + 1;
else if (key < sortedarray[mid])
last = mid - 1;
else return mid;
}
return -1;
}
int main()
{
int nums, a[100], finds;
cout<<"Please enter no. of inputs.";
cin>> nums;
for (int i=0; i<nums; i++)
{
cout<<"Please enter your inputs.";
cin>>a[i];
}
cout<<"enter the number you want to find.";
cin>> finds;
int found=binarysearch(a,0,nums,finds);
if(found!=-1)
cout<<"Value found at "<<found<<"pos";
else
cout<<"Value not found ";
return 0;}
|
|
#4
|
|||
|
|||
|
oh my. really thanks alot. grateful to u man.
now im gonna try to understand the code. thanks again! =D |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Outputting Binary search |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|