【发布时间】:2018-03-12 03:19:48
【问题描述】:
这是一个作业,这是书中提供的排序示例。这是二元归并排序还是自然归并排序?
#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);
}
我知道自然合并排序使用递归,这似乎是这里使用的方法。但是,我不确定。我们必须使用自然归并排序和二元归并排序并报告结果并讨论结果。
【问题讨论】:
-
这对我来说看起来很递归。
-
这确实使用了递归。
merge_sort方法调用自身,根据定义它是递归的。这是自然的归并排序。 -
“自然归并排序”和“二元归并排序”将是学术术语,它们的含义正是您的教授选择它们的含义。由于我们不是您的教授,也无法读懂您教授的想法,所以您不会在这里得到很好的帮助。现在“自然运行合并排序”是维基百科上的内容,可能是您认为教授所说的“自然合并排序”,但同样不是读心术。
-
建议:由于这显然是家庭作业,您最好以一种或另一种方式提出论点,并询问您是否遗漏了任何证明您错了的东西。 Stack Overflow 的家庭作业很酷,只是处理方式不同。期待更多的指导而不是直接的答案。