简体   繁体   中英

How to find the index of the smallest element recursively in python

I want to find the index of the smallest number in an element. If the list is: [5,6,4,3,8,9] How would I find it and return the index with a function that has parameters like this:

def smallest(table, first, last)

table: the list

first: index 0 of the list

last: is the last index of the list

The following bisects the input list recursively to find the index of the minimum:

def smallest(table, first, last):
    if last - first <= 1:
        return first if table[first] <= table[last] else last
    mid = first + (last - first) // 2
    left = smallest(table, first, mid)
    right = smallest(table, mid + 1, last)
    return left if table[left] <= table[right] else right

print(smallest([5, 6, 4, 3, 8, 9], 0, 5)) # 3

Another way is to shorten the interval ( firstlast ) by one at each recursion, while comparing the head and the smallest from the tail:

def smallest(table, first, last):
    if first == last:
        return first
    smallest_tail = smallest(table, first + 1, last)
    return first if table[first] <= table[smallest_tail] else smallest_tail

print(smallest([5, 6, 4, 3, 8, 9], 0, 5)) # 3

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