链表排序中为什么归并比快排好?

Posted zugle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表排序中为什么归并比快排好?相关的知识,希望对你有一定的参考价值。

One of the main sources of efficiency in quicksort is locality of reference, where the computer hardware is optimized so that accessing memory locations that are near one another tends to be faster than accessing memory locations scattered throughout memory. The partitioning step in quicksort typically has excellent locality, since it accesses consecutive array elements near the front and the back. As a result, quicksort tends to perform much better than other sorting algorithms like heapsort even though it often does roughly the same number of comparisons and swaps, since in the case of heapsort the accesses are more scattered.

Additionally, quicksort is typically much faster than other sorting algorithms because it operates in-place, without needing to create any auxiliary arrays to hold temporary values. Compared to something like merge sort, this can be a huge advantage because the time required to allocate and deallocate the auxiliary arrays can be noticeable. Operating in-place also improves quicksort‘s locality.

When working with linked lists, neither of these advantages necessarily applies. Because linked list cells are often scattered throughout memory, there is no locality bonus to accessing adjacent linked list cells. Consequently, one of quicksort‘s huge performance advantages is eaten up. Similarly, the benefits of working in-place no longer apply, since merge sort‘s linked list algorithm doesn‘t need any extra auxiliary storage space.

That said, quicksort is still very fast on linked lists. Merge sort just tends to be faster because it more evenly splits the lists in half and does less work per iteration to do a merge than to do the partitioning step.

 

快速排序效率的主要来源之一是引用的局部性,计算机硬件在这里得到了优化,因此访问彼此相邻的内存位置往往比访问分散在内存中的内存位置更快。快速排序中的分区步骤通常具有很好的局部性,因为它访问前后相邻的数组元素。因此,快速排序往往比其他排序算法(如堆排序)执行得好得多,尽管它通常执行的比较和交换次数大致相同,因为在堆排序情况下,访问更加分散。

此外,快速排序通常比其他排序算法快得多,因为它是就地操作的,不需要创建任何辅助数组来保存临时值。与归并排序相比,这是一个巨大的优势,因为分配和释放辅助数组所需的时间是显而易见的。就地操作还改进了快速排序的局部性。

 当使用链表时,这两个优点都不一定适用。因为链表单元格经常分散在内存中,所以访问相邻的链表单元格没有局部性的好处。因此,快速排序的巨大性能优势之一被耗尽了。类似地,就地工作的好处不再适用,因为merge sort的链表算法不需要任何额外的辅助存储空间。

 也就是说,快速排序在链表上仍然是非常快的。归并排序往往更快,因为它更平均地将列表一分为二,并且在每次迭代中进行归并比执行分区步骤所做的工作更少。

以上是关于链表排序中为什么归并比快排好?的主要内容,如果未能解决你的问题,请参考以下文章

链表排序(冒泡选择插入快排归并希尔堆排序)

编程-链表之希尔排序堆排序归并排序快速排序

js 归并排序

链表的快速排序和归并排序

148.排序链表

算法导论学习笔记-归并排序