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

2021-01-08 17:30

阅读:614

标签:归并排序   mem   benefit   临时   nec   oca   this   就是   ike   

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的链表算法不需要任何额外的辅助存储空间。

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

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

标签:归并排序   mem   benefit   临时   nec   oca   this   就是   ike   

原文地址:https://www.cnblogs.com/zugle/p/12966826.html


评论


亲,登录后才可以留言!