Problem in binary search using C++
-
I have copied a program from CrazyGeeks website and modified some of its statements. Anyone please tell me whats wrong in below code:
#include
using namespace std;int main()
{
int count, j, elements[50], search_num, first, last, mid;
cout<<"Enter the total number of elements :";
cin>>count;cout<<"\nEnter ">>count>>" numbers:\n";
for (j=0; j>elements[j];
}cout<<"\nWhich number that you want to search: ";
cin>>search_num;
first = 0;last = count-1;
mid = (first+last)/2;// binary search
while (first <= last)
{
if(elements[mid] > search_num){
first = mid + 1;
}else if(elements[mid] == search_num){
cout< last){
cout<Code link
-
I have copied a program from CrazyGeeks website and modified some of its statements. Anyone please tell me whats wrong in below code:
#include
using namespace std;int main()
{
int count, j, elements[50], search_num, first, last, mid;
cout<<"Enter the total number of elements :";
cin>>count;cout<<"\nEnter ">>count>>" numbers:\n";
for (j=0; j>elements[j];
}cout<<"\nWhich number that you want to search: ";
cin>>search_num;
first = 0;last = count-1;
mid = (first+last)/2;// binary search
while (first <= last)
{
if(elements[mid] > search_num){
first = mid + 1;
}else if(elements[mid] == search_num){
cout< last){
cout<Code link
Quote:
cout<<"\nEnter ">>count>>" numbers:\n";
Should be
out << "\nEnter " << count << " numbers:\n";
You should ask the user for an ordered sequence, in order to make the binary search work. Your code is very
C
-like, you didn't take advantange of the wonderful features of modernC++
. :-) -
Quote:
cout<<"\nEnter ">>count>>" numbers:\n";
Should be
out << "\nEnter " << count << " numbers:\n";
You should ask the user for an ordered sequence, in order to make the binary search work. Your code is very
C
-like, you didn't take advantange of the wonderful features of modernC++
. :-)Thank you very much
-
Thank you very much
-
I have copied a program from CrazyGeeks website and modified some of its statements. Anyone please tell me whats wrong in below code:
#include
using namespace std;int main()
{
int count, j, elements[50], search_num, first, last, mid;
cout<<"Enter the total number of elements :";
cin>>count;cout<<"\nEnter ">>count>>" numbers:\n";
for (j=0; j>elements[j];
}cout<<"\nWhich number that you want to search: ";
cin>>search_num;
first = 0;last = count-1;
mid = (first+last)/2;// binary search
while (first <= last)
{
if(elements[mid] > search_num){
first = mid + 1;
}else if(elements[mid] == search_num){
cout< last){
cout<Code link
You should format your code snippet with the proper indentations.