Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't heapsort lg(n!)?

I'm reading CLRS and it says heapsort is

HEAPSORT(A):
BUILD-MAX-HEAP(A);
for (i = A.length; i >= 1; i++)
{
    exchange A[1] with A[i];
    A.heap-size = A.heap-size - 1; 
    MAX-HEAPIFY(A,1);
}

MAX_HEAPIFY is O(lg n). The book says it runs MAX-HEAPIFY n times thus it is O(n lg n) time.

But if the heap is shrinking in size by 1 each iteration shouldn't it be O(lg n!) ?

It would be lg 1 + lg 2 ... + lg(n-1) + lg (n) = lg(n!), right ?

like image 460
user3504876 Avatar asked Dec 25 '22 11:12

user3504876


1 Answers

Actually it's Stirling's Approximation:

O( log(n!) ) = O(nlogn)

like image 115
chrk Avatar answered Jan 05 '23 03:01

chrk