// This is a function to check if the given array is sorted or not by recurssion
#include<iostream>
using namespace std;
bool sorted(int arr[],int n)
{
if(n==1)
{
return true;
}
I am cofused here when n will reach 1 then it will return true to "restArray" after that if array is not sorted then how will "restArray" become false?
bool restArray = sorted(arr+1, n-1);
return (arr[0]<=arr[1] && restArray);
}
int main()
{
int arr[]={1,6,3,4,5};
cout<<sorted(arr,5);
return 0;
}
As in every recursion there are two cases
First the trivial case if (n == 1): An array of size 1 (ie only a single element) is always sorted. Thus it returns true and stops the recursion
And if n is still greater than 1, you do the recursive call and check if the array without the first element is sorted (bool restArray = sorted(arr+1, n-1)), then you check if the first element of the array is less than the second element (a[0] < a[1]). (btw I'd probably check for <= here) And finally you combine those two checks with &&.
So for your example, it will at some point in time check 6 < 3, which will return false thus the overall result will become false.
But for sake of optimization, I'd suggest to reorder your statements a bit, such that you won't need the recursive call, if the order of the first two elements in the array is already wrong. And as #Scheff's Cat mentioned in the comments: When you convert it to a tail recursion, any decdent compiler will be able to refactor that recursion into a (much cheaper) iteration ...
And I'd also check for n <= 1 otherwise you might end up in an infinite recursion if you method is (wrongly!) called with n = 0.
bool sorted(int arr[],int n)
{
if (n <= 1)
{
return true;
}
return arr[0] <= arr[1] && sorted(arr+1, n-1);
}
or even simpler
bool sorted(int arr[], int n) {
return n <= 1
? true
: arr[0] <= arr[1] && sorted(arr+1, n-1);
}
Related
i have to find the index of an integer in an array using a recursive function this is what i have up to now:
#include <iostream>
int linear_search(int array[], int choice_, int size) {
if (array[choice_] >= 0) {
return array[choice_];
}
else {
return -1;
}
}
for example if the:
int array[]= {3,4,7,8};
if i type that i want to search for number 3 it should give me the index of 0 but instead it gives me the number 8. can i get some advise please?
Recursion is about narrowing down a problem to a smaller problem.
In the case of this particular search, try to think of it in terms of the found-item being either in the first position in the array, or maybe in the remainder of the array. This then reduces the problem to searching a smaller array, until you either find the item or you hit the trivial case of an empty array.
int linear_search(int array[], int choice_, int size)
{
// Array is empty -- not found
if (size <= 0)
return -1;
// Found at position 0
if (array[0] == choice_)
return 0;
// TODO: Search position in remaining array
int pos = linear_search(/* USE BRAIN HERE */);
// TODO: You may want to do something to the result before returning it
return pos;
}
As you can see, I've left some parts for you to fill in. I have faith in you. You can do it!
Happy coding!
This is binary search. It is a recursive function.
int binary_search_recursive(const int b[], int search_key, int low, int high)
{
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (search_key == b[mid])
return mid;
else if (search_key < b[mid])
return binary_search_recursive(b, search_key, low, mid - 1);
else
return binary_search_recursive(b, search_key, mid + 1, high);
}
This code is wrong
if (array[choice_] >= 0) {
return array[choice_];
When you do array[choice_] you are looking at the array value at index choice_. That is not what you want. Instead you want to find out if the array at some index is equal to choice_. That would be if (array[some_index] == choice_) return some_index;
Further, to make this a recursive approach, the function needs to call itself. Your code doesn't do that so it's not recursive.
Here is a recursive approach:
int searchArray(const int* array, const int choice_, const int size)
{
if (size > 0)
{
if (array[size-1] == choice_) return size-1; // Hit! Return the index
return searchArray(array, choice_, size-1); // Recursive call - pretend array is 1 shorter
}
return -1;
}
The code looks at the last element in the array.
If it is a hit it simply returns the index.
If it is not a hit, it calls itself but decrements size to pretend that the array is one element shorter.
In this way it goes from the end of the array towards the start of the array while looking for choice_.
BTW: Notice that it's a very bad idea to use recursion for this task - never do that! Use a simple for loop. But I guess this is just another example of a very bad homework task...
My program should build a number (in the k parameter) which is obtained with each of the even digits in the a[] array. n is the number of elements of the array.
void F (int n, int a[], int &k) {
if (n == 0)
{
if (a[0] % 2 == 0)
{
k = a[0];
}
else
{
k = -1;
}
}
else
{
F(n - 1, a, k);
if (a[n] % 2 == 0)
{
k = k * 10 + a[n];
}
}
}
BTW I'm not that good at recursion. It might not be an okay algorithm. I'm trying to get better.
The problem is as follows: if I cout k, it shows me -858990820.
If I use a cout k in the else condition to see what's happening, the result is fine UNTIL some point it suddenly turns into that negative number.
[
I think that number appears because of the array. It goes out of bounds at some point but I don't get when.
Calling F(n-1, a, k) at the beginning of the else condition should have resolved this. (because the array stops at n-1 and if I call that in the else condition as the first thing in there it should not ever reach n).
Can you explain to me what's happening and help me fix it?
////edit:
I forgot to mention: if there is no even number, k equals -1.
You have a problem here:
else
{
F(n - 1, a, k);
if (a[n] % 2 == 0)
{
k = k * 10 + a[n];
}
}
If your initial call to this function is:
int a[10];
F(100, a, &k);
Then accessing a[n] is going to access a[10], which is beyond the allocated bounds of the array. Remember that in C, array indexes are 0 through n; in this case, 9 is the index of the last item.
Given X, M, N where X = element to be searched in an array and N = access only first N elements in an array and M = array size, how do we find an element in an array with maximum (N+1) comparisons?
For example,
A = [3,5,2,9,8,4,1,6,7] here M = 9
Let's have N = 6 and X = 5 => So for this case, access only first 6 elements of an array and try to find whether X is present in it or not? Here answer will return true. But for X = 6 answer will be false.
This problem is not about time complexity. it's about number of comparisons you make. For example, Brute force method looks like this.
void search(vector<int> A){
for(int i=0; i<N; i++){ // [i < N is also comparison which is N times]
if(A[i] != X) continue; // [N comparisons ]
else return true;
}
return false;
}
Time complexity is O(n) but number of comparisons will be 2*N. Reduce this comparisons to (N+1). I tried to solve it but did not get solution. Is there any solution actually for this?
Idea
Modify N+1-th element to have X value and eliminate range check. Then once you have found element with X value (which is going to be true if M < N), check it's index (this is a last check that you can perform). If it's equal to N+1 then you haven't found one.
Analysis
Despite that the approach eliminates comparisons duplication, it's still has one "extra" comparison:
bool search(int* a, int n, int x)
{
a[n] = x;
int idx = 0;
while (a[idx] != x) // n + 1 comparisons in case if value hasn't been found
++idx;
return idx < n; // (n + 2)-th comparison in case if value hasn't been found
}
Solution (not perfect, though)
I can see only one way to cut that extra comparison with this approach: is to use the fact that zero integer value converts to false and any integer value not equal to zero converts to true. Using this the code is going to look like this:
bool search(int* a, int n, int x)
{
a[n] = x;
int idx = 0;
while (a[idx] != x) // n + 1 comparisons in case if value hasn't been found
++idx;
return idx - n; // returns 0 only when idx == n, which means that value is not found
}
Currently, I have the following recursive algorithm to solve the subset sum problem. It checks whether any combination of elements in a given vector sum up to a target number. For example, If A= {1,2,3,4,5} and target = 8, then it should return true as 1+2+5=8. Currently it works perfectly. However I want to make one change to it. I assign values to one of the function parameters in my main and I'm trying to not do that. All I want to do is call the function in my main. Not sure how I would attempt doing that. Any help is appreciated!!
bool subsetsum_imp(vector<int> & vec, int n, int sum) {
if (sum == 0) {
return true;
}
if (n == 0 && sum != 0) {
return false;
}
if (vec[n-1] > sum)
return subsetsum_imp(vec, n-1, sum);
return subsetsum_imp(vec, n-1, sum) || subsetsum_imp(vec, n-1, sum-vec[n-1]);
}
The value n is assigned in my main as follows or else the algorithm doesn't work, How can I incorporate this into my function somehow so I don't have to write it in my main?
int n = sizeof(vec)/sizeof(vec[0]);
Use a wrapper function that calls the recursive function. Something like:
bool subsetsum( vector<int> & vec, int sum )
{
return subsetsum_imp( vec, vec.size(), sum );
}
#include <iostream>
using namespace std;
int recursiveMinimum(int [], int n);
int main ()
{
int theArray[3] = {1,2,3};
cout << recursiveMinimum(theArray, 0);
cout << endl;
return 0;
}
// pass in array and 0 to indicate first element
// returns smallest number in an array
int recursiveMinimum (int anArray[], int n) // nth element is smallest element in anArray
{
while (anArray[n+1] != NULL)
{
int smallest = n;
if (anArray[n+1] <= anArray[n])
smallest = n + 1;
//if last element has not been reached
return recursiveMinimum(anArray, smallest);
}
}
My function exits, but it doesn't return anything. I tried to set the base case to when the outside of the array is reached. The return 0 line in main is reached so I'm pretty sure the base case in my function is being reached.
Here is the working function:
#include <iostream>
using namespace std;
int recursiveMinimum(int a[],int min,int index,int size);
int main()
{
int a[6] = {8, 2, 55, 3, 11, 9};
cout << recursiveMinimum(a,a[0],1,6) << endl;
return 0;
}
// pass in the array, the first element,
// 1 to indicate 2nd element, and the number of elements
int recursiveMinimum(int a[],int min,int i,int size)
{
if(i == size )
return min;
else if(i < size)
{
if(a[i] < min)
recursiveMinimum(a,a[i], i + 1, size);
else
recursiveMinimum(a,min, i + 1, size);
}
}
Thank you to everyone who helped. Due to time constraints I sent out a SOS (Stack Overflow distress Signal), however next time I will definitely step through the debugger prior to asking a question.
Have you stepped through this in a debugger? It should become fairly obvious when you do.
You are recursing within the while loop:
while( condition )
recursive call
while( condition )
recursive call
.
.
.
Instead what you probably were thinking was
if( condition )
recursive call
recursive call
recursive call
you see? Get rid of the while and replace it with an "if" statement.
You need to have an end case with a recursive function.
At the moment, your function always returns itself. This will recurse until the stack runs out. You need to have a check that says "I'm done", which will return a value rather than the result of another function call.
Because your while loop never terminates. Why are you sure anArray[n+1] will ever be NULL?
You never break your recursion. Actually I wonder that this compiles as your function doesn't even have a defined return value in case it reaches the end. Also using while there seems unnecessary as the function execution stops after the return anyway.
Instead of
int recursiveMinimum(int array[], int n);
I think that recursiveMinimum should be defined as
int recursiveMinimum(int array[], int index, int length);
with the intention that recursiveMinimum will return the minimum value in array between indexes index and length (i.e., min array[i] where i in [index, length)). Of course, you want to define this recursively. So then I would note that the minimum value in array between indexes index and length is
min(array[index], recursiveMinimum(array, index + 1, length));
Of course, there are boundary cases (such as when index = length - 1). In this case you would just return array[index] as the minimum.
Hope this helps. Let me know if this does not make sense.
You're misunderstanding the point of a recursive function. If a certain condition is true, then you return the result of a call to the recursive function, otherwise you return some other value. For example, here is a recursive definition of the factorial function (e.g. 5!, or "5 factorial", is 5*4*3*2*1, which is 125):
int
factorial (int n)
{
if (n == 1)
return n;
return (n * factorial (n - 1));
}
How it works:
If n is 1, then return 1 since 1! is 1.
Otherwise, return n multiplied by one less than n.
For example, if n is 5, then the return value is the result of the expression 5 * factorial (5 - 1), which is the same as 5 * factorial (4). Of course, the same thing happens again since it's a recursive function and 4 is not 1. So you end up with 5 * factorial (4), which is the same as 5 * (4 * factorial (4 - 1)), or 5 * (4 * factorial (3)).
You should be able to see the pattern now and how the factorial function works. Your recursiveMinimum function should adhere to the same general idea -- if something is true (or not true), return the result of a call the function (possibly with some additional things like the value n inside the factorial function needs to be multiplied by the result of the factorial function), else return a certain value and code the function to handle it appropriately. In other words, you need a "final" exit condition, such as the n == 1 condition in the factorial function above.
Good luck!
int recursiveMinimum(int a[],int min,int index,int size)
{
if(index == size )
return min;
else if(i < size)
{
if(a[i] < min)
recursiveMinimum(a,a[i],++index,size);
else
recursiveMinimum(a,min,++index,size);
}
}
int main()
{
int a[] = {1,2,3,0,-4};
int min = recursiveMinimum(a,a[0],1,5));
return 0;
}
When you use recursion make sure that you must put some exit condition to end it ,otherwise you will have in infinite recursion and you program will hang.
I think finding minimum is more efficient,easy and simple using iteration rather than recursion.