Skip to main content

Posts

Use of Memoization in Recursion

Memoization can be used to reduce function calls or computations. In the following example of Fibonacci series generation through C++, I will use normal recursion and then will change the same for memoization( http://en.wikipedia.org/wiki/Memoization ) to show the reduction of the function call. This is a simple demo implementation. static int counter = 0; int normalfibrecursion(int n) { if( n < 1) { return 0; } if(n == 1) { return 1; } if(n < 3) { return 1; } else { cout << "Call normalfibrecursion(" << n-2 << ") and normalfibrecursion(" << n-1 << ")\n"; counter++; return normalfibrecursion(n-2) + normalfibrecursion(n-1); } } In the above-mentioned simple prototype implementation for the Fibonacci series of n=10, the total function call comes to (54*2) times. This is usually very high and it will grow exponentially as n increases. Below mentioned picture demonstrates the fact: USE OF MEM...

Generic Swap without using template

The idea behind this was, I wanted to write a function that will take two parameters of the same type as a parameter and then it will swap them. It is a kind of generic swap but without the use of a C++ template. So the best way of doing it using "void *" as a parameter. As we know "void *" represents any arbitrary type that actually eases my job of writing a generic swap function. So, the function signature can be like below: void swap(void *arg1, void *arg2); "void *" points to the starting address of the arbitrary location in the memory, irrespective of the bit pattern. Try to write the function like the below: void swap(void *arg1, void *arg2) { void temp = *arg1; arg1 = *arg2; *arg = temp; } Oops, this is full of errors. 1. We can't declare a variable of type "void". 2. "void *" can't be dereferenced. 3. We also interested in swapping values. So, number of bytes making up the values to be pass...