Algorithm questions for daily brushing questions 0003

Ideas for recursive problems:

1: Find duplicates

        1.1: Find a method of division For example: cut a piece of cake smaller and smaller and hand over the sub-problems to the next function for realization

        1.2: Find a recursive formula For example: the recursive formula of the Fibonacci problem is f(n) = f(n-1) + f(n-2)

2: Find the amount of change

        2.1: The amount of change is generally used as a parameter of the recursive formula

3: Find the recursive exit

        3.1: Recursion must have an exit

Topic 1: Insertion sort using recursion

accomplish:

#Attention must pay attention to the subscript of this index, which is very, very important

def fThree(ls, k):
    if k == 0:
        return
    fThree(ls, k-1)
    index = k-1
    x = ls[k]
    while x < ls[index] and index >=0:
        ls[index+1] = ls[index]
        index -= 1
    ls[index+1] = x
if __name__ == "__main__":
    ls = [7, 4, 8, 9, 3, 2, 4, 4, 2]
    fThree(ls, 8)
    print(ls)

Guess you like

Origin blog.csdn.net/qq_50709355/article/details/123345099
Recommended