从递归向后选择排序函数调用 max 和交换函数
calling max and swap functions from a recursive backwards selection sort function
家庭作业:我需要编写一个递归向后选择排序函数,不使用循环,该函数调用提供的swap
函数和具有不同参数的find_Max
函数(此处仅称为max(。
要驱动swap
,我需要max
值的索引;我不知道如何得到它。 不幸的是,我不允许将任何参数更改为swap
、Max
或back_rec_sort
。 第一个功能是问题;必须调用另外两个。 此外,向后排序意味着找到最大值,将其交换到位置 n-1,然后朝向 0 索引。
//Updated version calling linear search from back_rec_sort as hw question
does not restrict that.
void rec_ssort(int arr[], int n)
{
int last = n -1;
if (last >= 0)
{
int Max = max(arr, 0, last);
//int index=binarySearch(arr, 0, last, Max);
int index = search(arr, last, Max);
swap(arr, index, last);
rec_ssort(arr, n - 1);
}
else
return;
}
// Linearly search x in arr[]. If x is present then return its
// location, otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
int max(int arr[], int start, int end)
{
//Base case when there is only 1 element left
if (start == end)
{
return arr[start];
}
//Compute middle element position
int m = (start + end) / 2;
//Calling the same function with reduced size
int left_max = max(arr, start, m);
int right_max = max(arr, m + 1, end);
//Combining solutions
if (left_max > right_max)
{
return left_max;
}
else
{
return right_max;
}
}
void swap(int arr[], int i, int j)
{
int temp;
temp =arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
写下这个,以便我们可以存档问题......
(1( 编写一个线性搜索函数,该函数获取数组和一个值,然后返回数组中该值的索引。
int search(int arr[], int n, int target)
{
int i;
for (i = 0; i < n; i++)
{
if (arr[i] == target)
return i;
}
return -1; // if not found
}
(2( -1 失败返回导致数组访问越界——这是原始代码和搜索函数之间的协调问题。 删除该行将返回 NULL,从而生成所需的功能。
如原始帖子中所述,家庭作业的要求并没有限制调用附加函数,因此我在程序中添加了一个线性搜索函数,从back_rec_sort内部调用它。 但是,我一直在数组中得到一个十六进制乱码,如注释中链接的那样,所以我按照 Prune 的建议进行了调试,从搜索函数中删除了"return -1"并且它可以工作。 我想了解更多关于如何确定测试、调试和编写断言的极端情况的信息。
相关文章:
- C++嵌套if语句,基本货币交换
- <streamsize>C++ 中 numeric_limits::max() 的值
- 黑客级别的Mini-Max Sum
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- shell排序中的交换和比较
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 通过交换元素使数组相同
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- 关于 std::min, std::max 中的比较运算符的混淆
- 交换运算符 + 重载会导致无限递归
- 为什么 std::reduce 需要交换性?
- 复制和交换习惯用法与移动操作之间的交互
- C++ - 没有自定义交换功能的移动分配运算符?
- 如何在数组中交换最小和最大的位置?
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 尽管一切看起来都很好,但值不会交换
- C++交换来自同一类成员的参数值,处理多个类
- std::max() 函数与定点实现的比较中的问题
- 使用 CImg 库的 std::min 和 std::max 的编译问题
- 从递归向后选择排序函数调用 max 和交换函数