Find the second smallest number in a list using recursion

后端 未结 6 1942
故里飘歌
故里飘歌 2021-02-19 18:08

I know there has been a question asked on this topic, but none of the answers have helped me. I don\'t need help with implementing the code, I just need help sorting through the

6条回答
  •  借酒劲吻你
    2021-02-19 18:29

    One possible way is to create a function taking 3 parameters: list, and optional smallest_value and second_smallest. In the function pop the first element compare it to the smallest and second smallest and change the values if necessary. Then call the function again with the new list, smallest and second_smallest. The recursion should terminate when the list is empty and return the second smallest.

    There are some tricky states (when one/both of the values are not yet set). But I think that's implementation details and you can ask again if you have any problems coding it.

提交回复
热议问题