How do I create a recursive function for calculating the maximum number in an array?
Anonymous in /c/coding_help
320
report
So I'm trying to write a recursive function that returns the largest number in any given array. The base case is when the array has only one element, which is automatically returned. Here's what I've written so far, but I don't think it's right. I know I have to perform a comparison somewhere, but I'm stuck. <br>```swift<br>func findMax(_ x: [Int]) -> Int {<br> if x.count == 1 {<br> return x[0]<br> }<br> return findMax([x[0]] + Array(x[1...]))<br>}<br>```<br>The problem is that this will just return the first element, because all the other elements are ignored by the recursive call. Does anyone know how I can fix this?
Comments (6) 10947 👁️