| sdsu619 (30) | |||
Hey I am trying to use recursion to write this function
And it works fine,as long as there is a negative. However, if there is no negative in the array, such as {1,2,3}, in this case it will return 2 instead of -1. Anyone have an idea of how to solve this? Im not allowed to use any for, while, loops etc. | |||
|
Last edited on
|
|||
| JLBorges (1752) | |||
This is one way (which is tail-recursive):
| |||
|
|
|||
| sdsu619 (30) | |
| Hey thanks for the reply. Unfortunately i failed to mention that im also not allowed to change the parameters. | |
|
|
|
| JLBorges (1752) | |||
Not tail-recursive:
| |||
|
|
|||
| tntxtnt (83) | |||||||||||
|
here's my explanation for JLBorges code: from your function
the only problem is when there is no negative in the array, or firstNegative(a+1, n-1) return -1, so let's add an exception for that:
You can stop here, or think further to shorten your code as JLBorges did: in the special case, because next==-1 so instead of return -1 we can return next, or 0 + next
as you can see, the function returns [0 or 1] + next, depends on next==-1(0) or next!=-1(1), so we can simply use (next!=-1) (which returns false/true or 0/1) to replace [0 or 1]
| |||||||||||
|
|
|||||||||||
| sdsu619 (30) | |||
Ah thanks for the help, just started learning recursive functions and they seem quite difficult... Im now working on
How can i compare one number in the array to the rest though? | |||
|
Last edited on
|
|||
| JLBorges (1752) | |||
|
> How can i compare one number in the array to the rest though? You do not need to compare one number with all the other numbers in the array, but just with one other number (which is the largest so far).
| |||
|
|
|||
| sdsu619 (30) | |||
How can i store the largest number in the array so far without another function? So using only the function header
| |||
|
Last edited on
|
|||
| JLBorges (1752) | |
|
> How can i store the largest number in the array so far without another function? The function would then need to move the elements of the array in a way that the largest number in the array so far is at a known position. Such a function would be a bad function; it would not be const-correct. | |
|
|
|
| sdsu619 (30) | |
| Hm in that case I must be missing something. Thanks for your responses though, very helpful. | |
|
|
|
| vlad from moscow (3650) | |||
My five cents.
| |||
|
Last edited on
|
|||