Just a cute pic of me
by Mike McKee
Programming

Iterative vs Recursive Functions

66 Days of Math and Programming -- day 24

The first time I saw someone call a function within itself, I thought they were out of their freaking mind. It seemed illegal.

I assumed calling a function within itself would open an infinite loop that runs a program forever.

What a rookie mistake, am I right?

While working on a Leet Code problem yesterday, I came across problem 35 (Search Insert Position) where you have to go through a sorted list, search for a target number, then return that index for where the number is (or should be). 

I thought for a while and had some good ideas to solve the problem but came up with nothing.

So I looked up other Leet Code solutions and realized the two words that matter the most…

Binary Search

I haven’t studied Data Structures and Algorithms yet (although ironically, I just bought a book about it), so the words binary search go right over my head.

But I’m not one to give up.

I researched how binary search works, and that’s when I came across two ways to do the search:

  1. Iterative
  2. Recursive

Let’s take a very brief look at the two…

Iterative Function

An iterative function is when you set a list of instructions and repeatedly execute them.

With Python, this usually involves “for” loops or “while” loops.

Here’s an example of using an iterative function to solve a binary search problem…

how an iterative function works

Recursive Function

A recursive function is where a function calls itself within itself.

Yeah, a lil tongue twister there.

Here’s an example of using a recursive function to solve a binary search problem…

how a recursive function works

Wrap It Up

I know this blog post doesn't go in-depth on the two functions, but that's because I have a lot to learn about data structures and algorithms. Luckily one of the first chapters in my book is all about recursion, so maybe I'll write about this more over the next few days.