简体   繁体   中英

comparisons using merge sort vs selection sort

I have an array of 10 int, and using selection sort I calculate it takes about 45 comparisons to sort the whole array, but I'm not sure how many it takes to sort using merge sort by my calculation it takes 12 comparisons.... am I right or wrong here?

Thanks in advance

here's the merge method

static void merge(int[] first, int[] second, int[] a)
    {
        int iFirst = 0;
        int iSecond = 0;
        int i = 0; 
        //moving the smaller element into a
        while(iFirst < first.length && iSecond < second.length)
        {
            if(first[iFirst] < second[iSecond])
            {
                a[i] = first[iFirst];
                iFirst++;
            }
            else
            {
                a[i] = second[iSecond];
                iSecond++;
            } 
            i++;             
        }
        counter += i;

        //copying the remaning of the first array
        while(iFirst < first.length)
        {
            a[i] = first[iFirst];
            iFirst++; i++;
        }
        //copying the remaining of second array
        while(iSecond < second.length)
        {
            a[i] = second[iSecond];
            iSecond++; i++;
        }        
    }

To merge an n -element array with an m -element array, you need n+m-1 comparisons in the worst case ( min{m,n} in the best).

So when you split the 10-element array in half, the top-level merge needs up to 9 comparisons. The two 5-element halves need up to 4 comparisons each, makes 9 + 2*4 = 17 . Splitting the 5-element halves in a 2-element and a 3-element part requires up to 1 + 3 comparisons, so the total worst case would be 25 comparisons (9 + 2*4 + 2*3 + 2*1).

                10(9)                             9
               /     \
              /       \
             /         \
            /           \
           /             \
          /               \
         /                 \
        5(4)               5(4)                   8
       /   \              /   \
      /     \            /     \
    3(2)     2(1)      3(2)     2(1)              6
   /   \    /   \     /   \    /   \
  2(1)  1  1     1   2(1)  1  1     1             2
 /   \              /   \
1     1            1     1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM