Is there ever a good reason to use Insertion Sort?

前端 未结 7 2132
再見小時候
再見小時候 2020-11-27 14:48

For general-purpose sorting, the answer appears to be no, as quick sort, merge sort and heap sort tend to perform better in the average- and worst-case scenarios. However, i

7条回答
  •  隐瞒了意图╮
    2020-11-27 15:07

    If you're talking about maintaining a sorted list, there is no advantage over some kind of tree, it's just slower.

    Well, maybe it consumes less memory or is a simpler implementation.

    Inserting into a sorted list will involve a scan, which means that each insert is O(n), therefore sorting n items becomes O(n^2)

    Inserting into a container such as a balanced tree, is typically log(n), therefore the sort is O(n log(n)) which is of course better.

    But for small lists it hardly makes any difference. You might use an insert sort if you have to write it yourself without any libraries, the lists are small and/or you don't care about performance.

提交回复
热议问题