Find index of maximum number in array using recursion in python
To find the index of the maximum number in an array using recursion in Python, you can use the following implementation:
def find_max_index(arr): if len(arr) == 1: return 0 else: max_index = find_max_index(arr[1:]) return (max_index + 1) if arr[0] < arr[max_index + 1] else 0 arr = [4, 6, 2, 8, 5] max_index = find_max_index(arr) print(max_index) # Output: 3
This function takes an array arr as an argument and returns the index of the maximum element in the array. It first checks if the length of the array is 1, in which case it returns 0 as the index of the only element in the array.
Otherwise, it makes a recursive call to find_max_index with the array slice arr[1:] as the argument. This recursively finds the index of the maximum element in the rest of the array.
Finally, it compares the first element of the original array arr[0] with the element at the index max_index + 1 (which is the index of the maximum element in the rest of the array), and returns either the index 0 or (max_index + 1) based on which element is larger.
Comments
Post a Comment