when is insertion sort faster than merge sort?

后端 未结 2 747
猫巷女王i
猫巷女王i 2021-02-04 22:41

For a homework problem, I was told that insertion sort runs at 8n^2 and that merge sort runs at 64(n(lg n)). As part of the solution I was given, it said that insertion sort was

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 23:04

    It came from this (algebraic) line of reasoning

    steps_in_insertion_sort <= steps_in_merge_sort
    8n^2 <= 64n lg n
    n^2 <= 8n lg n
    n <= 8 lg n
    

    Then 43 works by trial and error, or by solving for the zero of the equation n - 8 lg n = 0.

    For hacking by trial and error, note:

    $ python
    >>> 8 * log(43)/log(2)
    43.41011803761678
    

    Because "lg" means log-base-two.

    (Aside: calculations like this do not really translate to any real-world indication that one algorithm will beat another. Seriously, exactly 43?)

提交回复
热议问题