Exactly how many comparisons does sort merge?

I read that quicksort is much faster than merging in practice, and the reason for this is a hidden constant. Well, the solution for randomized quicksort is 2nlnn = 1.39nlogn, which means that the constant in quicksort is 1.39. But what about a merger? What is a constant in mergesort?

+5
source share
4 answers

Let's see if we can solve this!

In merge sort at each recursion level, we do the following:

  • Divide the array in half.
  • Sort each half recursively.
  • Use the merge algorithm to combine the two halves together.

, ? , ; . 2 () - ; . 3 n/2 . n , , , , n .

, :

C(1) = 0
C(n) = 2C(n / 2) + n

( , (n - 1), . .)

, n = 2 k k:

C'(0) = 0
C'(k) = 2C'(k - 1) + 2^k

: 0, 2, 8, 24,.... , k 2 k . , k = 0, 0, k 2 k 0. , k k + 1. 2 (k 2 k) + 2 k + 1= k 2 k + 1 + 2 k + 1= (k + 1) 2 k + 1 k + 1, . , C '(k) k 2 k. n = 2 k , , , n - , ,

C (n) = n lg n

, , quicksort! ? , . , quicksort , , , . , quicksort , , . , , , . , . , , , , . , . quicksort, . , , .

, , Wikipedia , n lg n , quicksort.

, !

+16

n

n ⌈lg n⌉ - 2 ⌈lg n⌉ + 1

lg n 2- n.

, .

+3

( ) k . m k+m-1 , min{k,m} . ( , , .)

C(n) - () n.

C(1) = 0, C(2) = 1, . ,

C(n) = C(floor(n/2)) + C(ceiling(n/2)) + (n-1)

C(n) <= n*log_2 n

, , ( ε > 0 , (1-ε)*n*log_2 n ), mergesort 1.

+2

Merge sort is O (n log n), and at each step in the “worst” case (for the number of comparisons) a comparison is performed.

Quicksort, on the other hand, is O (n ^ 2) in the worst case.

0
source

All Articles