Is there ever a good reason to use Insertion Sort?

前端 未结 7 2120
再見小時候
再見小時候 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:18

    Yes, there is a reason to use either an insertion sort or one of its variants.

    The sorting alternatives (quick sort, etc.) of the other answers here make the assumption that the data is already in memory and ready to go.

    But if you are attempting to read in a large amount of data from a slower external source (say a hard drive), there is a large amount of time wasted as the bottleneck is clearly the data channel or the drive itself. It just cannot keep up with the CPU. A natural series of waits occur during any read. These waits are wasted CPU cycles unless you use them to sort as you go.

    For instance, if you were to make your solution to this be the following:

    1. Read a ton of data in a dedicated loop into memory
    2. Sort that data

    You would very likely take longer than if you did the following in two threads.

    Thread A:

    1. Read a datum
    2. Place datum into FIFO queue
    3. (Repeat until data exhausted from drive)

    Thread B:

    1. Get a datum from the FIFO queue
    2. Insert it into the proper place in your sorted list
    3. (repeat until queue empty AND Thread A says "done").

    ...the above will allow you to use the otherwise wasted time. Note: Thread B does not impede Thread A's progress.

    By the time the data is fully read, it will have been sorted and ready for use.

提交回复
热议问题