Why is Insertion sort better than Quick sort for small list of elements?

前端 未结 6 670
不知归路
不知归路 2020-12-01 07:47

Isn\'t Insertion sort O(n^2) > Quicksort O(n log n)...so for a small n, won\'t the relation be the same?

6条回答
  •  -上瘾入骨i
    2020-12-01 08:34

    Good real-world example when insertion sort can be used in conjunction with quicksort is the implementation of qsort function from glibc.

    The first thing to point is qsort implements quicksort algorithm with a stack because it consumes less memory, stack implemented through macros directives.

    Summary of current implementation from the source code (you'll find a lot of useful information through comments if you take a look at it):

    1. Non-recursive

    2. Chose the pivot element using a median-of-three decision tree

    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving insertion sort to order the MAX_THRESH items within each partition. This is a big win, since insertion sort is faster for small, mostly sorted array segments.

    4. The larger of the two sub-partitions is always pushed onto the stack first

    What is MAX_THRESH value stands for? Well, just a small constant magic value which

    was chosen to work best on a Sun 4/260.

提交回复
热议问题