如何解决如何为这个递归函数制定确切的操作成本?
我被要求计算此函数的确切操作成本数。我已经使用 op 来跟踪它。递归调用应该是该函数调用执行的操作数(我不确定我的代码是否正确)。我的问题是,我如何制定一个数学方程来匹配操作次数。我在每一行旁边进行了注释,以注释操作成本。从中,我得到 2n^2 - n + 6。但这与我的输出不匹配。
// ParaM: arr is array to be sorted,n is size of array,i should initially = 0
int ssort(int arr[],int n,int i)
{
int op = 0;
if (i < n-1) //1
{
// Find and swap smallest remaining
int next = i + 1; //1
int smallest = i; //1
while (next < n) //i+1
{
if (arr[next] < arr[smallest]) //i
{
smallest = next; //i
}
next++; //i
op += 4; altogether 4 ops
}
op++; //while loop terminates
// Swap i with smallest
int temp = arr[i]; //1
arr[i] = arr[smallest]; //1
arr[smallest] = temp; //1
op += ssort(arr,n,i + 1);
}
op+=6;
return op;
}
解决方法
要找到公式,您可以简单地测试多个案例,然后从中插入一个公式。
// set up an empty array of length 10
int arr[10];
// set up a for loop for i = 1,2,3...
for(auto i : {1,3,4,5,6,7,8,9})
{
std::cout << ssort(arr,i,0) << ",";
}
打印:
6,17,32,51,74,101,132,167,206,249,
现在将该数据放入 polynomial interpolation calculator,您将得到:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。