我的教授警告我要避免“假递归”,其中一个函数的行为是递归的,但是没有任何有用的递归工作。我相信我理解递归,但想再检查一遍。
我编写了一个简短的递归排序程序,它对给定数组进行排序(我希望是递归的),而忽略了第一个元素。在对第一个元素之后的所有元素进行排序之后,它将第一个元素放置在排序子数组中的正确位置(通过向左移动元素)。
守则如下:
#include <iostream> // for cout
using namespace std;
void RecSort(int*, int, int); //RecSort function declaration
int arr[8] = {4,1,2,7,5,9,0,2}; //global array to sort (just an example)
void RecSort(int* arr, int len, int curr) { //RecSort definition
if (curr < len - 2) { //-1 to agrre with 0 indexing, -1 to stop 1 element before the end (terminating condition)
RecSort(arr, len, curr + 1); //recursively sort all elements except first element
}
for (int i = curr; i < len - 2; i++) { // once the rest of the array is sorted, shift elements to the left of the first element
if (arr[i] > arr[i + 1]) { // while appropriate (in this case, sort ascending order)
int temp = arr[i + 1]; //swap array elements if needed
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
int main() {
int length, current;
RecSort(arr, length = 8, current = 0);// sort array (recursively?)
for (int i = 0; i < length - 1; i++) {
cout << arr[i] << " "; //print array to verify functionality
}
}
这看起来是真正的递归吗?
发布于 2015-12-09 19:07:08
我从来没有遇到过“错误递归”这个术语,听起来这可能是你的教授的原创术语。因此,很难判断他认为什么是合格的。我假设他意味着可以使用循环而不是递归轻松地重写函数,因此它不需要是递归的。
一般的经验法则是,如果一个函数需要递归,它会多次调用自己。当一个函数只调用自己一次时,通常可以将其重写为一个循环。
在您的示例中,您要做的是对最后一个元素进行排序,然后对最后两个元素进行排序,然后对最后三个元素进行排序,等等。您可以将其实现为循环,如下所示:
for (int startIndex = length - 1, startIndex >= 0; startIndex++) {
// do what you would have done before.
这里所做的是实现一个插入排序,它通常不是以递归的方式实现的。
https://softwareengineering.stackexchange.com/questions/304671
复制相似问题