简体   繁体   English

使用合并排序与选择排序进行比较

[英]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? 我有一个10 int的数组,并使用选择排序我计算它需要大约45个比较来整理整个数组,但我不确定通过我的计算使用合并排序进行排序需要多少才需要进行12次比较...我在这里是对还是错?

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). 要将n元素数组与m元素数组合并,在最坏的情况下需要进行n+m-1比较(最佳n+m-1 min{m,n} )。

So when you split the 10-element array in half, the top-level merge needs up to 9 comparisons. 因此,当您将10个元素的数组拆分为一半时,顶级合并最多需要进行9次比较。 The two 5-element halves need up to 4 comparisons each, makes 9 + 2*4 = 17 . 两个5个元素的一半最多需要4个比较,使得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). 将2元素和3元素部分中的5个元素分成两半需要最多1 + 3个比较,因此总体最差情况将是25个比较(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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