Iterate through the array to find the index of key using recursion. :param list_data: the list to be searched :param key: the key to be searched :param left: the index of first element :param right: the index of last element :return: the index of key value if found, -1 other
(list_data: list, key: int, left: int = 0, right: int = 0)
| 1 | def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: |
| 2 | """ |
| 3 | Iterate through the array to find the index of key using recursion. |
| 4 | :param list_data: the list to be searched |
| 5 | :param key: the key to be searched |
| 6 | :param left: the index of first element |
| 7 | :param right: the index of last element |
| 8 | :return: the index of key value if found, -1 otherwise. |
| 9 | |
| 10 | >>> search(list(range(0, 11)), 5) |
| 11 | 5 |
| 12 | >>> search([1, 2, 4, 5, 3], 4) |
| 13 | 2 |
| 14 | >>> search([1, 2, 4, 5, 3], 6) |
| 15 | -1 |
| 16 | >>> search([5], 5) |
| 17 | 0 |
| 18 | >>> search([], 1) |
| 19 | -1 |
| 20 | """ |
| 21 | right = right or len(list_data) - 1 |
| 22 | if left > right: |
| 23 | return -1 |
| 24 | elif list_data[left] == key: |
| 25 | return left |
| 26 | elif list_data[right] == key: |
| 27 | return right |
| 28 | else: |
| 29 | return search(list_data, key, left + 1, right - 1) |
| 30 | |
| 31 | |
| 32 | if __name__ == "__main__": |