在合并排序中选择中间元素
Selection of middle element in merge sort
对于下面给定的合并排序代码:
void merge(int a[], int bottom, int top, int mid){
int i = bottom;
int j = mid+1;
int k = bottom;
int c[50];
while (i <= mid&&j <= top){
if(a[i]<=a[j]){
c[k] = a[i];
i++;
k++;
}
else{
c[k] = a[j];
j++;
k++;
}
}
while (i <= mid){
c[k] = a[i];
k++;
i++;
}
while (j <= top){
c[k] = a[j];
k++;
j++;
}
for (int i = bottom; i < k; i++){
a[i] = c[i];
}
}
void mergesort(int a[], int bottom, int top){
if(bottom < top){
int mid = (bottom+top)/2;
mergesort(a, bottom, mid);
mergesort(a, mid+1, top);
merge(a, bottom, top, mid);
}
}
如果将合并排序调用更改为
mergesort(a, bottom, mid-1);
mergesort(a, mid, top);
这将导致运行时错误。
从算法方面,我没有看到任何区别。有人能指出这个变化出了什么问题吗?
假设底部为0,顶部为1,因为您调用了mergesort(a, 0, 1)
。则mid=(0+1)/2=0。则中间值1=-1。然后您将呼叫mergesort(a, 0, -1)
和mergesort(a, 0, 1)
(注意……这是我们开始的呼叫)。第一个调用将返回,因为它与bottom < top
条件不匹配,但第二个调用是无限递归。
如果您注意到,这个问题适用于mergesort(a, n, n + 1)
形式的所有调用,并且由于mergesort是一种分而治之类型的算法,因此您将非常频繁地进行此类调用。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 2D数组来自文本输入,中间有空格
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- C++:我可以重用/移动 std::list 元素从中间到结尾吗?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 使用 std::move 在开始时插入矢量的中间元素不起作用
- 当中间元素选择为枢轴时,快速排序C 不起作用
- 将元素插入到中间的矢量中
- 如何更改元素中间的文本样式
- std::multiset并查找中间元素
- 在合并排序中选择中间元素
- 删除单链表中间的元素
- 从中间删除元素的最佳数据结构是什么
- TinyXML2 -在XML中间插入元素
- 使用中间元素作为透视C++计算快速排序中的比较数
- 对于可移动类型,删除std::向量中间的元素仍然很昂贵吗
- 如何找到地图的中间元素??STL