这是什么类型的合并排序?

时间:2018-03-12 03:19:49

标签: c++ sorting mergesort

这是一项作业,这是本书中提供的排序示例。这是二进制合并排序还是自然合并排序?

 #include <iostream>

    #include "util.h"

    /** 
      Merges two adjacent ranges in a vector
     @param a the vector with the elements to merge
    @param from the start of the first range
   @param mid the end of the first range
   @param to the end of the second range
*/
void merge(vector<int>& a, int from, int mid, int to)
{  
   int n = to - from + 1; // Size of the range to be merged 
   // Merge both halves into a temporary vector b 
   vector<int> b(n);

   int i1 = from;
      // Next element to consider in the first half 
   int i2 = mid + 1;
      // Next element to consider in the second half 
   int j = 0; // Next open position in b 

   // As long as neither i1 nor i2 is past the end, move the smaller
   // element into b

   while (i1 <= mid && i2 <= to)
   {  
      if (a[i1] < a[i2])
      {  
         b[j] = a[i1];
         i1++;
      }
      else
      {  
         b[j] = a[i2];
         i2++;
      }
      j++;
   }

   // Note that only one of the two while loops below is executed

   // Copy any remaining entries of the first half
   while (i1 <= mid)
   {  
      b[j] = a[i1];
      i1++;
      j++;
   }
   // Copy any remaining entries of the second half
   while (i2 <= to)
   {  
      b[j] = a[i2];
      i2++;
      j++;
   }

   // Copy back from the temporary vector
   for (j = 0; j < n; j++)
      a[from + j] = b[j];
}

/**  
   Sorts the elements in a range of a vector.
   @param a the vector with the elements to sort
   @param from start of the range to sort
   @param to end of the range to sort
*/
void merge_sort(vector<int>& a, int from, int to)
{  
   if (from == to) return;
   int mid = (from + to) / 2;
   // Sort the first and the second half
   merge_sort(a, from, mid);
   merge_sort(a, mid + 1, to);
   merge(a, from, mid, to);
}

我知道自然合并排序使用递归,这似乎是这里使用的方法。但是,我不确定。我们必须使用自然合并排序和二进制合并排序,并报告结果并讨论结果。

1 个答案:

答案 0 :(得分:2)

您帖子中的排序是自然合并排序。二进制合并排序的作用类似于合并排序,以及在合并排序之前使用二进制插入排序的附加步骤。

这样做是为了将小型数据集上的插入排序效率与大型数据集合的排序效率相结合。

在此处查看“变体”部分:https://en.wikipedia.org/wiki/Insertion_sort#Variants

以下是相关的SO问题:Binary Merge sort & Natural Merge sort