Why does the worst-case cost of Quick sort in Algorithms 4th edition not match my calculated cost?

huangapple go评论59阅读模式
英文:

Why does the worst-case cost of Quick sort in Algorithms 4th edition not match my calculated cost?

问题

I'm reading the Algorithms 4th edition, and it tells me that Quick sort uses ~N^2/2 compares in the worst case since N+(N-1)+(N-2)+...+2+1=(N+1)N/2. However, the book also tells me that the cost of partitioning is always N+1. So I'm wondering why the cost of the worst case is not (N+1)+(N-1+1)+(N-2+1)+...+(2+1)+0 = (N+1)+N+...+3=(N+4)(N-1)/2?

英文:

I'm reading the Algorithms 4th edition, and it tells me that Quick sort uses ~N^2/2 compares in the worst case since N+(N-1)+(N-2)+...+2+1=(N+1)N/2. However, the book also tells me that the cost of partitioning is always N+1. So I'm wondering why the cost of worst case is not (N+1)+(N-1+1)+(N-2+1)+...+(2+1)+0 = (N+1)+N+...+3=(N+4)(N-1)/2?

答案1

得分: 2

他们犯了一个错误?快速排序的分区需要将枢轴与每个其他元素进行比较,这恰好是 N−1 次比较。在最坏的情况下,枢轴每次都是最小值或最大值元素,因此总比较次数是 (N−1) + (N−2) + … + 1 + 0 = N(N−1)/2,即所有配对。

英文:

They goofed? Quicksort partition needs to compare the pivot to each other element, which is exactly N−1 comparisons. In the worst case, the pivot is either the min or the max element each time, so the total number of comparisons is (N−1) + (N−2) + … + 1 + 0 = N(N−1)/2, which is all pairs.

huangapple
  • 本文由 发表于 2023年5月25日 23:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定