1
Chapter 7: Sorting (Heapsort, Mergesort) CE 221 Data Structures and Algorithms
Izmir University of Economics
CE 221 Data Structures and Algorithms Chapter 7: Sorting - - PowerPoint PPT Presentation
CE 221 Data Structures and Algorithms Chapter 7: Sorting (Heapsort, Mergesort) Text: Read Weiss, 7.5 7.6 Izmir University of Economics 1 Heapsort Priority queues can be used sort in O ( N log N ) time. First, build a binary
1
Izmir University of Economics
2
Izmir University of Economics
Izmir University of Economics 3
Max heap after buildHeap phase Max heap after first deleteMax phase
permutation of N distinct items is 2NlogN-O(NloglogN).
for any D, distinct deleteMax sequences total # of heaps with cost less than M is at most # of heaps with cost M < N(logN-loglogN-4) is at most (N/16)N. So the average # of comparisons is at least 2M.
Izmir University of Economics 4
) 2 ! ( ), ( log 2 ! log 2 log 2
2
N e N N N O N N N i
N N i
items N with heaps
number e N N f M s comparison
number d M Cost
N D N i i D
)) 4 /( ( ) ( 2 ,
1
D M D S N d d d D S 2 2 ... 2 2 1 2
M N M i i N
N N 2 ) (log 2 ) (log
1 1
5
Izmir University of Economics
required (since each comparison adds an element to C. It should also be noted that after N-1 elements are added to array C, the last element need not be compared but it simply gets copied).
If N=1 DONE else { mergesort(left half); mergesort(right half); merge(left half, right half); }
Izmir University of Economics 6
7
Izmir University of Economics
Izmir University of Economics 8
/* leftPos = start of left half, rightPos = start of right half Last copying may be avoided by interchanging the roles of the arrays a and tmpArray at alternate levels of recursion */
– T(1)=1 – T(N)=2T(N/2)+N // assumption is N=2k
Izmir University of Economics 9
) log ( log ) ( log 1 ) 1 ( ) ( ..... .......... .......... .......... 1 1 ) 1 ( 2 ) 2 ( 1 8 / ) 8 / ( 4 / ) 4 / ( 1 4 / ) 4 / ( 2 / ) 2 / ( 1 2 / ) 2 / ( ) ( N N O N N N N T N T N N T T T N N T N N T N N T N N T N N T N N T N N N N T N N NT N T N k use kN N T N T N N T N T N N T N T N N T N T
k k
log ) ( log ) 1 ( ) ( log , ) 2 / ( 2 ) ( 3 ) 8 / ( 8 ) ( 2 ) 4 / ( 4 ) ( ) 2 / ( 2 ) (
Izmir University of Economics 10