Binary Search with few modification - c++

While I am trying to compile the code with few modification in binary search recursive function. The program is acting weird. Some time it gives the correct value and some time it goes to infinite loop. Please explain what went wrong with the code. I am using DEV C++ as an IDE.
CODE:
#include<iostream>
#include<sstream>
using namespace std;
//function to compare the two integers
int compare(int low, int high)
{
if (low==high)
return 0;
if (low<high)
return 1;
else
return -1;
}
//Function for binary search using recursion
int *BinarySearch(int *Arr,int Val,int start,int end)
{
int localstart=start;
int localend=end;
int mid=(start+end)/3;
cout<<"MID:"<<mid;
int comp= compare(Val,Arr[mid]);
if(comp==0)
return &(Arr[mid]);
else if (comp>0)
return BinarySearch(Arr,Val,localstart,mid-1);
else
return BinarySearch(Arr,Val,mid+1,localend);
return NULL;
}
main()
{
int *arr;
arr= new int [256];
string str;
getline(cin,str);
stringstream ss;
ss<<str;
int index=0;
while(ss>>arr[index])
{index++;}
//cout<<arr[index-1];
cout<<"Enter Value:";
int value;
cin>>value;
int *final;
final=BinarySearch(arr,value,0,index-1);
if(final!=NULL)
cout<<"Final:"<<*final;
else
cout<<"Not Found";
getchar();
getchar();
return 0;
}

Two ideas:
What should BinarySearch do if Val is not in the array? Trace out what your code does in this case.
(start+end)/3 probably isn't the middle of the current range.

Related

Vector error,a very confusing segmentation error?

So basically,I am doing a code which searches for an element of a vector inside a vector.While I thought of the approach , implementing it got me a segmentation error. I narrowed down the problem
In the code if I decomment the line in the for loop while commenting the above then all elements of B[i] are being displayed.Why then is a segmentation error being thrown. I think the binary_return is more or less correct and if I replace the line with
binary_return(A,0,A.size(),B[1])
then its working.
Here is the code:
#include<iostream>
#include<vector>
using namespace std;
int binary_return(vector<int> a,int start,int end,int seek)
{
int mid = (start+end)/2;
//cout<<start<<" "<<seek<<" "<<mid;
if(end!=start)
{
if(a[mid]==seek)
{
return mid;
}
else if(a[mid]>seek)
{
return binary_return(a,start,mid,seek);
}
else if(a[mid]<seek)
{
return binary_return(a,mid,end,seek);
}
}
else
return -1;
}
int main()
{
vector<int> A{1,3,6,9,23};
vector<int> B{1,4,23};
cout<<B[0]<<B[1]<<B[2];
for(int i=0;i<B.size();i++)
{
cout<<binary_return(A,0,A.size(),B[i]);
//cout<<binary_return(A,0,A.size(),B[0]);
}
return 1;
}
Your code is not handling the last case correctly and ends up in infinite recursion.
This unfortunately in C++ means that anything can happen (you're not guaranteed to get a meaningful error).
Add a debug print at the beginning of the function and you'll see in which cases you're entering infinite recursion.
You have infinite recursion in third if statment
The correct code if the following:
#include<iostream>
#include<vector>
using namespace std;
int binary_return(vector<int> a,int start,int end,int seek)
{
int mid = (start+end)/2;
//cout<<start<<" "<<seek<<" "<<mid;
if(end!=start)
{
if(a[mid]==seek)
{
return mid;
}
else if(a[mid]>seek)
{
return binary_return(a,start,mid,seek);
}
else if(a[mid]<seek)
{
// In your sample you forgot to add +1 (mid+1) for next start
return binary_return(a,mid+1,end,seek);
}
}
else
return -1;
}
int main()
{
vector<int> A{1,3,6,9,23};
vector<int> B{1,4,23};
for(int i=0;i<B.size();i++)
{
cout<<binary_return(A,0,A.size(),B[i]);
}
return 0;
}

Finding LCS using DP

I have used Dynamic Programming to find longest common sub-sequence b/w two strings. What is wrong in the code. Why it always gives answer as 0?
#include<bits/stdc++.h>
using namespace std;
int dp[20][20];
void initialize()
{
for(int i=0;i<20;i++)
for(int j=0;j<20;j++)
dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
if(m==0||n==0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
if(a[m-1]==b[n-1])
return dp[m-1][n-1] = 1+lcs(a,b,m-1,n-1);
if(a[m-1]!=b[n-1])
return dp[n-1][m-1]=max(dp[n][m-1]=lcs(a,b,n,m-1),dp[n-1][m]=lcs(a,b,n-1,m));
}
int main()
{
string a="AGGTAB",b="GXTXAYB";
cout<<lcs(a,b,a.length(),b.length());
}
You've forgotten to call initialize()
18th line, it should be dp[m][n], not dp[m-1][n-1]
Commented 19th line code, as it is no need & for make the code compatible for all compilers
i.e., some compiler may give warning: control reaches end of non-void function [-Wreturn-type]
Made some code change in 20th line, as it seems you confused with variables m & n.
Code:
#include<bits/stdc++.h>
using namespace std;
int dp[20][20];
void initialize()
{
for(int i=0;i<20;i++)
for(int j=0;j<20;j++)
dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
if(m==0||n==0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
if(a[m-1]==b[n-1])
return dp[m][n] = 1+lcs(a,b,m-1,n-1);
//if(a[m-1]!=b[n-1])
return dp[m][n]=max(lcs(a,b,m-1,n),lcs(a,b,m,n-1));
}
int main()
{
string a="AGGTAB",b="GXTXAYB";
initialize();
cout<<lcs(a,b,a.length(),b.length());
}
Output:
4

Searching a string inside a char array using Divide and Conquer

Let's say that I have a struct array and each element has a name. Like:
struct something{
char name[200];
}a[NMAX];
Given a new string (char array), i need to find the correct index for it using divide and conquer. Like:
char choice[200];
cin>>chioce;
int k=myFunction(choice); // will return the index, 0 otherwise
// of course, could be more parameters
if( k )
cout<<k;
I don't know how to create that searching function (I tried, I know how D&C works but i'm still learning! ).
And no, i don't want to use strings !
This is what i tried:
int myFunction(char *choice, int l,int r) // starting with l==0 && r==n-1
{
int m;
if(strcmp(a[m].name,choice)==0)
return m;
else{
m=(l+r)/2;
return myFunction(choice,l,m-1);
return myFunction(choice,m+1,r);
}
}
This is my solution for your above problem. But i have modified a few things in your code.
#include<iostream>
using namespace std;
#define NMAX 10
struct something{
char *name; //replaced with char pointer so that i can save values the way i have done
}a[NMAX];
int myFunction(char *choice, int l,int r) // starting with l==0 && r==NMAX-1
{
if(l>r) //return if l has become greater than r
return -1;
int m=(l+r)/2;
if(strcmp(a[m].name,choice)==0)
return m+1;
else if(l==r) //returned -1 as the value has not matched and further recursion is of no use
return -1;
else{
int left= myFunction(choice,l,m-1);//replaced return
int right= myFunction(choice,m+1,r);//by saving values returned
if(left!=-1) //so that i can check them,
return left; //otherwise returning from here onlywould never allow second satatement to execute
if(right!=-1)
return right;
else
return -1;
}
}
int main(){
a[0].name="abc";
a[1].name="a";
a[2].name="abcd";
a[3].name="abcf";
a[4].name="abcg";
a[5].name="abch";
a[6].name="abcj";
a[7].name="abck";
a[8].name="abcl";
a[9].name="abcr";
char choice[200];
cin>>choice;
int k=myFunction(choice,0,NMAX-1); // will return the index, 0 otherwise
// of course, could be more parameters
if( k !=-1)
cout<<k;
else
cout<<"Not found";
return 0;
}
Hope it will help.

Heapsort using Priority queue C++

My code works for putting data into the array but when I print it out, it always crashes after first number. There must be something wrong with my bubbledown function, could you point out what is wrong with it? Thank you in advance.
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
void bubbleup(int pq[], int back);
void bubbledown(int pq[], int front, int back);
void swap(int &a, int &b);
int main(){
ifstream infile;
ofstream outfile;
string input, output;
int size,number;
int front=1, back=0;
int *pq=new int[size]; // dynamically allocate array
cout<<"What's the input file name?"<<endl;
getline(cin, input); // get the input name
infile.open(input.c_str());// open the input file
while(!(infile.eof())){
infile>>number; // infile to an integer type variable first instead of an array. this is why your program doesn't work!!!!!
back++;
pq[back]=number;
bubbleup(pq,back);
for(int i=1;i<=back;i++)
cout<<pq[i]<<" ";
cout<<endl;
}
cout<<"what's the output file name?"<<endl;
getline(cin, output);
outfile.open(output.c_str());
while(back!=0){
cout<< pq[front]<<endl;
outfile<< pq[front]<<endl;
pq[front]=pq[back];
back--;
bubbledown(pq,front,back);
}
}
//bubbleup function
void bubbleup(int pq[], int back)
{
int fatherindex=back/2;
while(!(pq[back]>=pq[fatherindex])||!(back==1)){
if(pq[back]<pq[fatherindex])
swap(pq[back],pq[fatherindex]);
back=fatherindex;
fatherindex=back/2;
}
}
//bubbledown function
void bubbledown(int pq[], int front, int back){
int fatherindex=front,kidindex;
while(2*fatherindex+1 <= back){
kidindex=2*fatherindex+1;
if((kidindex+1<back) && (pq[kidindex]<pq[kidindex+1])){
kidindex++;
}
if(pq[fatherindex] > pq[kidindex]){
swap(pq[fatherindex],pq[kidindex]);
fatherindex=kidindex;
}
else
return;
}
}
//swap function
void swap(int &a, int &b){
int t=a;
a=b;
b=t;
}
A few problems to look at
You don't initialize size before using it, so your pq memory could be any size at all.
You are using 1-based access to your arrays, so make sure you allocate one more than you need.
while(!back==0) will work, but it is doing boolean logic on an int, then comparing the result with an int. while(back!=0) is a lot easier to read and will produce fewer compiler warnings.
Edit: also your bubbleDown function has an infinite loop when neither if test is triggered.

Input not terminating because of a comment

This cpp code is not terminating. I have tried the code by various inputs but this is not terminating.I think there is a bug in the 52th line, when I comment the 52 line than the code is working fine.
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
// binary search for larger elements
using namespace std;
vector <int > q;
// bsearch value uses hte
#define bvector q // just define these values to use them in your functin
#define VALUE(x) bvector[x]
int b_search(int value){
int low=0,high=bvector.size(),mid;
mid=(low+high)/2;
cout << "In the bsearch";
while(low<high)
{
if(VALUE(mid)==value)
return mid;
else if(VALUE(mid)>value)//
high=mid;
else if(VALUE(mid)<value)
low=mid+1;
}
if(VALUE(low)>value)
return low;
return -1;
}
int main(){
int i;
for(scanf("%d",&i);i;scanf("%d",&i))
q.push_back(i); // this is for taking input in the vectot
sort(q.begin(),q.end());
for(i=0;i<q.size();i++)
printf("%d ",q[i]);// for printing the sorted
int j;
printf("Enter the elements you want to search");
int x;
scanf("%d",&x);
// BUG is present in this lines
cout <<"This is the end of scanf";// if this line is commented then the 54th line is not reached
j=b_search(x);
printf("%d ",j);
return 0;
}
The statement : mid=(low+high)/2; is a bit misplaced. It should be inside the while loop.
This is probably what is causing an infinite loop.