Binary Search Recursion warning - c++

#include <iostream>
using namespace std;
int i = 0;
int binarySearch(int arr[],int left, int right, int item)
{
int midpoint;
bool found{false};
if(left < right && !found)
{
midpoint = left + (right - left)/2;
if(arr[midpoint]<item)
{
binarySearch(arr,midpoint+1,right,item);
}
else if(arr[midpoint]>item)
{
binarySearch(arr,left,midpoint-1,item);
}
else
{
found = true;
return midpoint;
}
}
}
int main()
{
int arr[] = {10,20,30,40};
int x = binarySearch(arr,0,3,40);
cout << x ;
}
How is it returning the correct value of the item searched for although its not even reaching the return statement.
It is reaching the base case when it is only one element in the array, but it should not reach the return statement, thus it should return garbage, but it is returning the correct index every time.

In most cases you don't return any value so you get whatever happens to be in the result register or stack slot at the time. This can work by accident, if you are unlucky.
Turn on compiler warnings and always fix them. Best to turn warnings into errors.

Related

Error: Char 34: runtime error: addition of unsigned offset to 0x603000000070 overflowed to 0x60300000006c (stl_vector.h) (C++)

I have been trying to solve the sorted Squares leetcode problem (https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3240/), and I am mostly through it. However, I get the above error. Following is my code
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int start = 0;
int end = nums.size()-1;
vector<int> final(nums.size());
int finalIdx = final.size()-1;
int sqr = 0;
while(start<=end){
if (abs(nums[start])<abs(nums[end])){
sqr = nums[end]*nums[end];
final[finalIdx] = sqr;
finalIdx--;
end--;
}
if (abs(nums[start])>abs(nums[end])){
sqr = nums[start]*nums[start];
final[finalIdx] = sqr;
finalIdx--;
start++;
}
else if(abs(nums[start])==abs(nums[end])){
sqr = nums[end]*nums[end];
final[finalIdx] = sqr;
finalIdx--;
final[finalIdx] = sqr;
finalIdx--;
start++;
end--;
}
return final;
}
}
};
The issue lies in my loop condition I believe. When I change the condition to start<end, I have no compile error, but the first element of the output array (final) is always 0, which I assume is by default. However, when I try to do start<=end in order to add a condition that handles the start==end case, I get the above error. I would like to understand why this is happening so I can rectify the issue. Thanks!
First, that's not a "compile error" ; it's a runtime error (and the error message reported says as much.
That said, the issue stems from the condition of start <= end landing on the = part of that condition. Eventually that is guaranteed to happen, save for one very specific set of circumstances:
start = (end-1)
abs(num[start]) == abs(num[end])
When that happens, your code will dump two values to the output vector, and both increment start and decrement end. The start and end indexes effectively swap values, the while condition is no longer true, and the loop will now cleanly exit.
In all other circumstances start and end will eventually land on the same index. When that happens your dual-push logic will dump the same value twice into the target vector, and that is where the issue manifests. There is only one value left to push (and start and end both reference it by index). Therefore you're going to push one more value into your target vector than you have space for, and the runtime exception ensues.
The fix is simple. Stop trying to be smart about short circuiting in three different conditions when in reality you only need one and a master-else. The computational requirements are the same no matter what, and in the end all you need is this:
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int> const &nums)
{
std::vector<int> final(nums.size());
int start = 0;
int end = nums.size()-1;
int finalIdx = final.size()-1;
while(start<=end)
{
if (abs(nums[end]) < abs(nums[start]))
{
final[finalIdx--] = nums[start]*nums[start];
++start;
}
else
{
final[finalIdx--] = nums[end]*nums[end];
--end;
}
}
return final;
}
};
If you really want all three conditions in your code, it is possible, but not warranted, and the special case circumstances don't justify doing it. Regardless, see below:
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int> const &nums)
{
std::vector<int> final(nums.size());
int start = 0;
int end = nums.size() - 1;
int finalIdx = final.size() - 1;
while (start <= end)
{
if (abs(nums[start]) < abs(nums[end]))
{
final[finalIdx--] = nums[end] * nums[end];
end--;
}
else if (abs(nums[end]) < abs(nums[start]))
{
final[finalIdx--] = nums[start] * nums[start];
start++;
}
else // !(a<b || b<0) implies (a == b)
{
int sqr = final[finalIdx--] = nums[end] * nums[end];
if (end != start)
{
final[finalIdx--] = sqr;
}
--end;
++start;
}
}
return final;
}
};

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;
}

Adding int to long

I am creating a recursive formula to add up all the elements in a vector. The problem them I'm having is that my result is not adding to the vector results so it always returns 0. I have tried static_cast to turn it into an int but I'm still not able to figure it out. Here's my code:
long vectorSum(const std::vector<int>& data, unsigned int position) {
int ret = 0;
if(position == data.size()-1) {
return ret;
} else {
ret += data[position];
return vectorSum(data, position+1);
}
}
I am calling the function like this:
std::vector<int> test1;
for(int i = 0; i < 10; i++) {
test1.push_back(i);
}
cout << vectorSum(test1, 0) << "\n";
This is not correct:
ret += data[position];
return vectorSum(data, position+1);
The new value of ret (+= data[position]) isn't being used anywhere or passed back to the caller.
Remeber: ret is strictly local to each invocation of vectorSum(). It doesn't exist outside of your vectorSum(); it's being set to "0" every time you invoke vectorSum().
long vectorSum(const std::vector<int>& data, unsigned int position) {
if(position == data.size())
return 0;
else
return data[position]+vectorSum(data, position+1);
}
Then call it as
int sum=vectorSum(data,0);
Normally, one adds to the value of a recursive call. You are not doing that. In your code, it will keep calling with a modified position until it hits the terminating condition, then that return 0; goes all the way back up to the caller.
long vectorSum(const std::vector<int>& data, unsigned int position) {
int ret = 0;
if(position == data.size()-1) {
return ret;
} else {
ret += data[position]; //this line has no affect on the result!
return vectorSum(data, position+1); //you don't accumulate anything
//this will always return 0
}
}
Instead, you want to add the current value plus the value from the recursive call:
long vectorSum(const std::vector<int>& data, unsigned int position) {
if(position == data.size()-1) {
//terminating condition, return 0
return 0;
} else {
//add current value plus value from processing the rest of the list
return data[position] + vectorSum(data, position+1);
}
}
As a side note: recursion is a great tool, but it can easily be misused by applying it to problems that already have better and more elegant solutions. For this, something like std::accumulate would probably be the most "natural" solution for C++.

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.

Implementing min function

Good day, I found this priority queue implementation and I am trying to get a min version of it (instead of max). I have no idea where to start. I tried mixing the signs of the functions (naive attempt) but it didn't get me far. Any help of how to implement it and a few words explaining it are very wellcome. The source is below:
Note I have left it's comments
#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
class PriorityQueue
{
vector<int> pq_keys;
void shiftRight(int low, int high);
void shiftLeft(int low, int high);
void buildHeap();
public:
PriorityQueue(){}
PriorityQueue(vector<int>& items)
{
pq_keys = items;
buildHeap();
}
/*Insert a new item into the priority queue*/
void enqueue(int item);
/*Get the maximum element from the priority queue*/
int dequeue();
/*Just for testing*/
void print();
};
void PriorityQueue::enqueue(int item)
{
pq_keys.push_back(item);
shiftLeft(0, pq_keys.size() - 1);
return;
}
int PriorityQueue::dequeue()
{
assert(pq_keys.size() != 0);
int last = pq_keys.size() - 1;
int tmp = pq_keys[0];
pq_keys[0] = pq_keys[last];
pq_keys[last] = tmp;
pq_keys.pop_back();
shiftRight(0, last-1);
return tmp;
}
void PriorityQueue::print()
{
int size = pq_keys.size();
for (int i = 0; i < size; ++i)
cout << pq_keys[i] << " ";
cout << endl;
}
void PriorityQueue::shiftLeft(int low, int high)
{
int childIdx = high;
while (childIdx > low)
{
int parentIdx = (childIdx-1)/2;
/*if child is bigger than parent we need to swap*/
if (pq_keys[childIdx] > pq_keys[parentIdx])
{
int tmp = pq_keys[childIdx];
pq_keys[childIdx] = pq_keys[parentIdx];
pq_keys[parentIdx] = tmp;
/*Make parent index the child and shift towards left*/
childIdx = parentIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::shiftRight(int low, int high)
{
int root = low;
while ((root*2)+1 <= high)
{
int leftChild = (root * 2) + 1;
int rightChild = leftChild + 1;
int swapIdx = root;
/*Check if root is less than left child*/
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
swapIdx = leftChild;
}
/*If right child exists check if it is less than current root*/
if ((rightChild <= high) && (pq_keys[swapIdx] < pq_keys[rightChild]))
{
swapIdx = rightChild;
}
/*Make the biggest element of root, left and right child the root*/
if (swapIdx != root)
{
int tmp = pq_keys[root];
pq_keys[root] = pq_keys[swapIdx];
pq_keys[swapIdx] = tmp;
/*Keep shifting right and ensure that swapIdx satisfies
heap property aka left and right child of it is smaller than
itself*/
root = swapIdx;
}
else
{
break;
}
}
return;
}
void PriorityQueue::buildHeap()
{
/*Start with middle element. Middle element is chosen in
such a way that the last element of array is either its
left child or right child*/
int size = pq_keys.size();
int midIdx = (size -2)/2;
while (midIdx >= 0)
{
shiftRight(midIdx, size-1);
--midIdx;
}
return;
}
int main()
{
//example usage
PriorityQueue asd;
asd.enqueue(2);
asd.enqueue(3);
asd.enqueue(4);
asd.enqueue(7);
asd.enqueue(5);
asd.print();
cout<< asd.dequeue() << endl;
asd.print();
return 0;
}
Well generally in such problems, i.e. algorithms based on comparison of elements, you can redefine what does (a < b) mean. (That is how things in standard library work by the way. You can define your own comparator.)
So if you change it's meaning to the opposite. You will reverse the ordering.
You need to identify every comparison of elements, and switch it. So for every piece of code like this
/*if child is bigger than parent we need to swap*/
if (pq_keys[childIdx] > pq_keys[parentIdx])
invert it's meaning/logic.
Simple negation should do the trick:
/*if child is NOT bigger than parent we need to swap*/
if !(pq_keys[childIdx] > pq_keys[parentIdx])
You do not even need to understand algorithm. Just inverse meaning of what lesser element is.
Edit:
Additional note. You could actually refactor it into some kind of bool compare(T a, T b). And use this function where comparison is used. So whenever you want to change the behaviour you just need to change one place and it will be consistent. But that is mostly to avoid work to look for every such occurrence, and stupid bugs and when you miss one.
Easier:
std::prioroty_queue<int, std::vector<int>, std::greater<int>> my_queue;
If this is part of an exercise, then I suggest following the standard library's design principles: split the problem up:
data storage (e.g. std::vector)
sorting or "heapifying" algorithm (c.f. std::make_heap etc.)
ordering criteria (to be used by 2. above)
Your class should give you some leeway to change any of these independently. With that in place, you can trivially change the "less-than" ordering for a "greater than" one.