很久没写博客了,今晚学习算法的东西,有个练习要用递归法来做插入排序,花了10多分钟弄出来了。
对我来说,迭代相对于递归更好理解,一直没有递归的思想,今天完全凭自己做出来了,别的不说,起码加深了对递归的理解。
/**
* 插入发现递归版
* @param a
*/
public void insertSortRecursive(int[] a) {
int r=a.length-1;
insertRecur(a,r);
}
private void insertRecur(int[] a, int r) {
if(r>0){
insertRecur(a, r-1);
insertRecursive(a,r-1,r);
}
}
private void insertRecursive(int[] a, int r, int k) {
int temp=a[k];
int i=r;
while(i>=0 && temp<a[i]){
a[i+1]=a[i];
i--;
}
a[i+1]=temp;
}
代码就这么简单,稍微测试了一下,可以用,但到了100000级,就报了栈溢出,但运行时间还是比迭代的插入要快些,因为只是单枝树,有n层,每层花费cn,效率还是Θ(n^2)
顺便也加上迭代的方法吧:
/**
* 插入排序
*
* @param test
*/
public void insertionSort(int[] test) {
for (int i = 1; i < test.length; i++) {
int j = i - 1;
int temp = test[i];
while (j >= 0 && temp < test[j]) {
test[j + 1] = test[j];
j--;
}
test[j + 1] = temp;
}
}
顺便,说一下,理解递归关键是理解divide-and-conquer
的思想,中文就是大事化小,小事化了,再复杂的东西,你只要把它的量级降下来,就会好解决得多了。