# How does this recursive algorithm work?

One question from the Grokking Algorithms book:

Implement a max([]int) function, returning the biggest element in the array.

Here's my solution in Golang (adapted from the Python solution in the book):

func maxNumber(arr []int) (r int) {
// base case
if len(arr) == 2 {
if arr > arr {
return arr
} else {
return arr
}
}

// recursive case
subMax := maxNumber(arr[1:])

if arr > subMax {
fmt.Println("arr > subMax")
return arr
} else {
fmt.Println("arr < subMax")
return subMax
}
}


It works, but I can wrap my head around it. How is the third block called if every time maxNumber(arr[1:]) is called it executes the function again, passing the array with one last element? If so, at some point in time it will hit the first block (base case) and return or the first element or the second.

I know the function works, but I'm missing the how.

Could someone help me around, explain like I'm 5 styles haha

Thanks!

• arr[1:] is the list arr without its first element. So the array argument becomes shorter at each level of recursion, until finally it has only two elements, which is the base case. Does that help ? – gandalf61 Oct 9 '19 at 14:03
• By the way it doesn't work for an array of length 1, and making it work would make the algorithm simpler – harold Oct 9 '19 at 14:07