Quicksort slower than Mergesort?

后端 未结 15 1145
名媛妹妹
名媛妹妹 2021-02-07 02:01

I was working on implementing a quicksort yesterday, and then I ran it, expecting a faster runtime than the Mergesort (which I had also implemented). I ran the two, and while th

15条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 02:50

    One of the advantages of quicksort for relatively small array sizes is just an artifact of hardware implementation.

    On arrays, quicksort can be done in-place, meaning that you're reading from and writing to the same area of memory. Mergesort, on the other hand, typically requires allocating new buffers, meaning your memory access is more spread out. You can see both of these behaviors in your example implementations.

    As a result, for relatively small datasets, quicksort is more likely to get cache hits and therefore just tends to run faster on most hardware.

    Mergesort is still a pretty good solution for large data sets or other data structures, like linked lists, as your experiments confirm.

提交回复
热议问题