Wednesday, July 05, 2006

The Devilment that is Recusion

Recursion: (re·cur·sion)
see: Recursion

Scarily enough the Cambridge online dictionary or many spell check dosn't have it. Anyway I digress back to the story.

I was having a bad coding day, Trying to implement a binary search which I decided to make recusive. Spent the best part of a hour trying to work out where things went wrong before giving up and scratch writing it with iteration.

Now recursion does have its uses but what exactly is it the best thing for ?
I do like the clean minimalistic code it produces (student printing budget), but the statement that its easier to understand can be argued with. Simple functions can become difficult to trace when you have a big stack of parameters to keep track off as it burrows through the stack then snaps back at you.
Recurive functions offer no increase in performancece, actually reducing speed and increasing overhead as calls have to be made to the stack each time navigatete a level in the recursion.

But beforI i get death by flame. And due to the fact I'm a man of science :p lets look at the facts
Source
Recursion Vs iterationon
  • Neither is more computationally powerfull.
  • They are completely interchangeable. Anything done Recusively can be done iteratively
  • recursiveve algorithms do tend to look better with cleaner simpler code
  • iterativeve functions have less overhead as the calculations are done "inplace"

So Who wins ?? Neither to be fair. It all depends on your approach. If you really dig recursion then you can use it for everything. (Though iterating over a list would be overkill) The same applies to iteration. I suppose its just a matter of preference.

That said recursive code is neater and smaller than ititerativeve counterpart. Meaning it (should) be easier to understand and maintain. The trade off is speed and for some complicated functions algorithm complexity it can really make your brain hurt sometimes trying to work out that algorithm. That's what prompted this little rant in the first place.

Well back to the world of WSN's Till next time

1 comment:

Kemp said...

Just because you (sort of) mentioned it - a recursive linear search. I just wrote this off the top of my head, so I doubt it's the best way, but it works :-)

def get_index(list, item):
    if len(list) == 0: return -1
    if list[0] == item: return 0

    result = get_index(list[1:], item)
    if result == -1: return -1
    return result + 1