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

时间:2017-06-19 21:37:56

标签: c++ sorting recursion max swap

家庭作业:我需要编写一个递归向后选择排序函数,使用无循环,调用具有不同参数的提供的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;
}

2 个答案:

答案 0 :(得分:0)

如原始帖子所述,作业的要求并没有限制调用附加功能,所以我在程序中添加了一个线性搜索功能,从back_rec_sort中调用它。但是,我一直在数组中得到一个十六进制的乱码,如注释中所链接的那样,所以我按照Prune的建议调试,从搜索功能中删除了“return -1”并且它可以工作。我想了解更多有关如何确定测试,调试和编写断言的极端情况的信息。

答案 1 :(得分:0)

写这篇文章以便我们可以归档问题......

(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,这会产生所需的功能。