Merge sort for f sharp

后端 未结 2 756
清酒与你
清酒与你 2021-01-14 14:28

This is my code, when I enter a very large number I get stack overflow error does anyone know why? When i enter a very large number i get that error and im not really sure w

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 15:01

    Each recursive call requires stack space. The more times mergesort calls itself, the more stack is used.

    You avoid the stack overflow with recursive function by taking advantage of tail recursion. It simply means the last thing a function does is call itself, the call is removed and turns into a jump instead, saving stack space.

    This is tricky to do in your case because you have to call mergesort twice. Only one of them can be last. The solution is to use a continuation. You only call mergesort once, but pass it a function to call, which will call mergesort the second time.

    Search the internet for F# examples of a merge sort that uses continuations.

提交回复
热议问题