Recursive calls - recursion

Below code performs recursive calls.
int fib(int n){
if(n==0)
return 0;
return fib(n-1) + fib(n-2);
}
Will this recursive calls perform fib(n-2) call only after finishing till the last call of fib(n-1)? or both fib(n-1) and fib(n-2) occur concurrently for each of the current call?

Related

Why is the vertex captured after recursive call is done executing in topological sort using DFS

Here is a working code for topological sort using DFS algorithm:
void dfs(vector<int> g[], int s, vector<bool>& visited, vector<int>& res)
{
visited[s] = true;
for(auto i: g[s])
{
if(!visited[i])
{
dfs(g, i, visited, res);
}
}
res.push_back(s); // ???
}
//Function to return list containing vertices in Topological order.
vector<int> topoSort(int V, vector<int> adj[])
{
vector<int> res;
vector<bool> visited(V, false);
for(int i = 0; i<V; ++i)
if(!visited[i])
dfs(adj, i, visited, res);
reverse(res.begin(), res.end());
return res;
}
Why is res.push_back(s); done after the recursive call is done executing, and not before it is called?

Why iteration is so much more time-consuming than recursion?

Today when I am solving Fibonacci arrays, I meet with a very strange thing. Recursion only takes 16ms, but iteration takes 80ms. I have tried to optimize my iteration (such as I use a vector container to fulfill my stack) but iteration is still much slower than recursion. It doesn't make sense because recursion still builds a stack at OS level, which is more time-consuming than iteration.
Here is my iteration code:
class Solution {
public:
int fib(int n) {
std::stack<int, std::vector<int>> st;
st.push(n);
int result = 0;
int temp = 0;
while(!st.empty()) {
temp = st.top(); st.pop();
if(temp == 1) result++;
else if(temp == 0) continue;
else {
st.push(temp - 1);
st.push(temp - 2);
}
}
return result;
}
};
Here is my recursion code
class Solution {
public:
int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
else return fib(n - 1) + fib(n - 2);
}
};
Well, I have searched for the reason. According to Is recursion ever faster than looping?, recursion is more time-consuming than iteration in an imperative language. But C++ is one of the imperative languages, it is not convincing.
I think I find the reason. You can help me check if there is any incorrect in my analysis?
The reason why recursion is faster than iteration is that if you use an STL container as a stack, it would be allocated in heap space.
When the PC pointer wants to access the stack, cache missing might happen, which is greatly expensive as for a small scale problem.
However, as for the Fibonacci solution, the code length is not very long. So the PC pointer can easily jump to the function's beginning. If you use a static int array, the result is satisfying.
Here is the code:
class Solution {
public:
int fib(int n) {
int arr[1000];
arr[0] = n;
int s = 1;
int result = 0;
int temp;
while (s) {
temp = arr[s-1];
s--;
switch (temp) {
case 1:
result++;
break;
case 0:
continue;
break;
default:
arr[s++] = temp - 1;
arr[s++] = temp - 2;
}
}
return result;
}
};

how can i return an array and delete an array in C++ function?

//how can i return an array and delete an array?
int* classA :: aa(double* data, int length){
int* arr = new int[length];
for(int i=0; i<length; i++)
arr[i] = data[i];
// please look at this part
return arr;
delete[] arr;
}
i want to delete the array 'arr' after allocation and also want to return it.
how can i do both of them?
can i use :
x = ClassA.aa(data,length);
delete[] arr;
First of all the code with delete[] statement is never reached because of previous return statement. I think that you can't do both thinks, because if you delete arr and return pointer after this and will try access some element of it in future in
would be an undefined behaviour, because the memory is free. So if you want to use this pointer in future don't free memory. Free it when arr is not need.
X = ClassA.aa(data,length); delete[] X.

How do I convert my depth-first traversal code using recursion to the one using stack?

My data structures and stack operations are defined like this.
typedef struct AdjListNode{
int dest;
struct AdjListNode* next;
int visited;
}AdjListNode;
typedef struct AdjList{
struct AdjListNode* head;
}AdjList;
typedef struct Graph{
int V;
struct AdjList* array;
}Graph;
typedef struct Stack{
int top;
char items[MAX];
}Stack;
void Push(struct Stack *s,float val){
if(s->top == MAX-1){
printf("Error: Stack overflow.");
exit(1);
}else{
s->items[++(s->top)]=val;
}
}
float Pop(struct Stack *s){
if(s->top == -1){
printf("Error: Stack underflow");
exit(1);
}else{
return(s->items[(s->top)--]);
}
}
int isFull(struct Stack* s){
return s->top == MAX-1;
}
int isEmpty(struct Stack* s){
return s->top == -1;
}
And this function checks if there is a path from p to q
void FindPath_DepthFirstSearch(Graph* graph, int p, int q) {
AdjListNode* node = graph->array[p].head;
node->visited = 1;
// printf("%d\n", p);
if(p == q){
printf("Path found!\n");
exit(1);
}
while(node){
if (!graph->array[node->dest].head->visited)
FindPath_DepthFirstSearch(graph, node->dest, q);
node = node->next;
}
printf("Path not found!\n");
exit(1);
}
I'm fairly new to learning data strctures. The code works perfectly when I use recursion but I got stuck for a long time when I tried to implement this using stack. Can anyone help me with this? Thanks!
The basic idea when converting from a recursive definition to a loop-based one is that you store the data that you normally store in local variables on a stack (LIFO) container. Instead of recursing, you push additional elements on the stack. The code then looks like this:
function algorithm(args):
stack = new FIFO
# push initial state (e.g. root node for DFS)
stack.push(args)
# process all elements
while stack.has_elements():
# retrieve topmost element from stack
e = stack.pop()
# do something with the current element
e.frobnicate()
# push additional elements onto the stack
if e.condition1():
stack.push(e.derived1())
if e.condition2():
stack.push(e.derived2())

How to assign a pointer a 2D square array of unknown size?Whats wrong in the following function?

Here is the code I tried,Segmentation fault was the result..
void allocate(int ** universe,int n) // to assign pointer "a" a nXn matrix
{
universe=(int **) calloc(n,sizeof(int *));
int l;
for(l=0;l<n;l++)
universe[l]=(int *)calloc(n,sizeof(int));
int u;
for(l=0;l<n;l++)
for(u=0;u<n;u++) //making all entries 00
universe[l][u]=0;
}
Whats wrong in the following function?
Since arguments are passed by value, your function works on a copy of the passed-in pointer, and doesn't modify the pointer in the caller, that remains uninitialised (or still points where it pointed before), and you can't access the allocated memory from the caller, and trying to access it via universe[i][j] is likely to cause a segmentation fault. As a further consequence, when allocate() returns, you have lost the only pointers to the allocated memory and that's a leak.
The correct way to do it is to
return the pointer,
int ** allocate(int n)
{
int **universe = calloc(n,sizeof(int *));
if (!universe) {
fputs(stderr, "Allocation of universe failed.");
exit(EXIT_FAILURE);
}
int l;
for(l = 0; l < n; l++) {
universe[l] = calloc(n,sizeof(int));
if (!universe[l]) {
fprintf(stderr, "Failed to allocate row %d.\n", l);
exit(EXIT_FAILURE);
}
}
return universe;
}
and call that like int **universe = allocate(124);, or
pass in the address of the pointer you want to allocate memory to,
void allocate(int *** universe_addr,int n) // to assign pointer "a" a nXn matrix
{
int ** universe = calloc(n,sizeof(int *));
if (!universe) {
/* repair or exit */
}
int l;
for(l = 0; l < n; l++) {
universe[l]=(int *)calloc(n,sizeof(int));
if (!universe[l]) {
/* repair or exit */
}
}
/* Now set the pointer in the caller */
*universe_addr = universe;
}
and call it like allocate(&universe, 123);.
Note: I have removed the initialisation loop, since calloc already zeros the allocated memory, hence it is unnecessary to set it to 0 again.

Resources