从递归向后选择排序函数调用 max 和交换函数

calling max and swap functions from a recursive backwards selection sort function

本文关键字:max 交换 函数 函数调用 排序 递归 选择      更新时间:2023-10-16

家庭作业:我需要编写一个递归向后选择排序函数,不使用循环,该函数调用提供的swap函数和具有不同参数的find_Max函数(此处仅称为max(。

要驱动swap,我需要max值的索引;我不知道如何得到它。 不幸的是,我不允许将任何参数更改为swapMaxback_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"并且它可以工作。 我想了解更多关于如何确定测试、调试和编写断言的极端情况的信息。