KonkurStudy
همه کارت‌ها

k-Way Merge Time Complexity

Merging kk sorted lists with nn total elements costs Θ(nlog⁡k)\Theta(n\log k), which is O(n)O(n) only when kk is constant.

کارت مفهوم کنکور ارشد علوم کامپیوتر

اهمیت
۰/۵

Intuition

Merging kk sorted lists into one is done with a min-heap of size kk holding the current front element of each list. You repeatedly extract the global minimum and push the next element from the list it came from. Each of the nn output elements pays one extract-min plus one insert, each O(log⁡k)O(\log k).

Result

cost=Θ(nlog⁡k)\text{cost} = \Theta(n\log k)

  • kk a constant cc: Θ(nlog⁡c)=Θ(n)=O(n)\Theta(n\log c)=\Theta(n)=O(n), because log⁡c\log c is just a constant factor.
  • kk growing with nn: the log⁡k\log k factor stays. The extreme k=nk=n (all singleton lists) turns merging into a full comparison sort, forcing the Ω(nlog⁡n)\Omega(n\log n) comparison lower bound. So linear time is impossible.

Worked example

Merge k=nk=n lists of size 11 in O(n)O(n)? That would sort nn arbitrary keys with O(n)O(n) comparisons, contradicting Ω(nlog⁡n)\Omega(n\log n). Hence only constant kk gives O(n)O(n).

build min-heap from heads of all k lists   // O(k)
repeat n times:
    x = extractMin()                       // O(log k)
    output x
    insert next element of x's list        // O(log k)
// total: Theta(n log k)

Pitfall: Do not treat k=2k=2 as the magic boundary. Every fixed kk (e.g. 33, 1010) merges in O(n)O(n) since log⁡k\log k collapses to a constant; the real divide is constant kk versus kk that scales with nn.

فرمول‌های کلیدی

k-way merge cost
Θ(nlog⁡k)\Theta(n\log k)

Heap-based merge of $k$ sorted lists with $n$ total elements.

Comparison-sort lower bound
Ω(nlog⁡n)\Omega(n\log n)

When $k=n$ (singleton lists), merging equals sorting, forcing this bound.

#k-way-merge#merge#min-heap#lower-bound#comparison-model#complexity

سوالات تمرینی