【发布时间】:2018-05-09 21:43:44
【问题描述】:
我正在尝试使用递归算法进行插入排序,但它不能包含任何类型的迭代循环。 这是我写的代码;它似乎不起作用
class Sort {
public int shift(int[] a, int j, int k){
if(j>=0 && k< a[j]){
a[j + 1] = a[j];
j--;
shift(a,j, k);
}
return j;
}
public void IS(int a[], int i){
int j, temp;
if(i<a.length){
j = i-1;
temp = a[i];
a[shift(a,j,temp)+1]=temp;
IS(a,i+1);
}
}
}
IS() 中的i 从 1 开始。
我对我的 shift() 方法感到困惑。如果使用下面的代码,那么它可以工作。我正在尝试将 while 循环转换为递归算法,但我总是得到错误的输出。
while (j >= 0 && temp<data[j]) {
a[j + 1] = a[j];
j--;
}
【问题讨论】:
-
我对这个问题投了反对票,因为没有证据表明对此代码执行了任何调试。请edit您的问题向我们展示您的调试发现了什么,以及关于特定代码行的特定问题。请参阅:How to create a Minimal, Complete, and Verifiable example 和 How to Debug Small Programs
-
对不起,我没有意识到。我对stackoverflow相当陌生。我会把它拿下来。