ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Introduction to Algorithms, CLRS] Exercise 1.2-2
    알고리즘 2017. 8. 15. 11:25

    This is a solution for Introduction to Algorithms. I write this for my study purpose.


    1.2-2

    Suppose we are comparing implementations of insertion sort and merge sort on the same machine. For inputs of size n, insertion sort runs in 8n2 steps, while merge sort runs in 64n lg n steps. For which values of n does insertion sort beat merge sort? 

    Answer:

    So the question is when the following will be...:

    8n2   < 64n lg n

    We can solve this equation as follows:

    It is obvious that insertion sort runs at quadratic time which is definitely worse than merge sort’s linearithmic time for very large values of n. We know for n=1, merge sort beats insertion sort. But for values greater than that, insertion sort beats merge sort. So, we will start checking from n=and go up to see for what value of n merge sort again starts to beat insertion sort.

    Notice that for ,  will be a fraction. So, let’s start with  and check for values of n which are power of 2.

    n=828/8=21=2<8 n=16216/8=22=4<16 n=32232/8=24=16<32 n=64264/8=28=256>64


    Somewhere between 32 and 64, merge sort starts to beat insertion sort. Let’s do what we were doing but now we are going to try middle value of either range, repeatedly (binary search). 

    n=32+642=48248/8=64>48 n=32+482=40240/8=32<40 n=40+482=44244/8=44.8>44 n=40+442=42242/8=38.4<42 

    So, at n=44, merge sort starts to beat insertion sort again. Therefore, for 1<n<44, insertion sort beats merge sort.


    source: http://atekihcan.github.io/CLRS/E01.02-02/




    댓글

Designed by Tistory.