简体   繁体   中英

Finding the maximum integer in an array with recursion

I don't even know where to start with this exercise. I have been looking at it for 2 hours without knowing what to do. I have been told to write a method taking an array of integers, and a range of indices (low and high).

I have been given the hint that the base case should be when low == high , returning as a maximum the value in the range (which should be array[low] ). Then, if we have more than one element in the range of the array, we can split it up, find the maximum in each piece and find the maximum of the maxima. However, I don't know how to proceed. I tried using the method by definining two new numbers, maxRange(array, low, (low+high)/2) and maxRange(array, (low+high)/2, high) , and trying to do a sort of comparison, but I'm not sure on how to go on.

What you need to do is keep dividing the array in 2 halves until you are left with only one element. This is the base case.

In each recursion step, call maxRange on the lower half, and maxRange on the upper half. These will return the maximum integer in those two ranges. Now if we know the maximum integer in the lower half, and in the upper half, then clearly the biggest integer in both halves is the greater of the two. Make sense?

Another explanation:

When designing recursive functions, try to pretend that you've already done it and the function works as expected. So, while you're still writing maxRange pretend that it already does what you want: given an array, a "low" integer (the start of the range, inclusive) and a "high" integer (the end of the range, not inclusive), it returns the biggest integer in that range. Then, we just write the function maxRange that divides the problem into smaller parts for recursion until the base case. When we hit the base case (low == high - 1) , we just return array[low] , since there's only one element. Remember, depending on the way you define your function (if high is inclusive), the base case can be either (low == high) or (low == high - 1) . Try it out on paper! Remember that integer arithmetic returns only the integer part of a division: 3/2 is 1.

What language are you using? If you are using c# you can do...

int[] arr = {1 , 2 , 3 ,4}; int max = arr.Max();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM