本文地址: http://blog.csdn.net/caroline_wendy/article/details/17099693
递归(recursive)是一种程序设计方式, 可以使程序精巧(compact)和优雅(elegant);
递归包含三个规则(rules):
1. 递归需要一个基本示例(base case), 且第一个语句(statement)必须是一个返回语句(return);
2. 递归的子问题是基本示例的较小(smaller)的问题, 并且收敛(converge)于基本示例(base case);
3. 递归的子问题必须是互斥(disjoint), 不能重叠(ovelap);
非递归模式: http://blog.csdn.net/caroline_wendy/article/details/17068019
使用递归的二分查找, 代码如下:
/* * Algorithms.java * * Created on: 2013.12.03 * Author: Wendy */ /*eclipse std kepler, jdk 1.7*/ import java.util.Arrays; public class Algorithms { public static int rank(int key, int[] a) { return rank(key, a, 0, a.length-1); } public static int rank(int key, int[] a, int lo, int hi) { if (lo>hi) return -1; int mid = lo + (hi-lo)/2; if (key < a[mid]) return rank(key, a, lo, mid-1); else if (key > a[mid]) return rank(key, a, mid+1, hi); else return mid; } public static void main(String[] args) { int[] a = {1, 3, 4, 5, 2, 6, 7, 8, 9, 0}; Arrays.sort(a); int[] b = {4, 11, 5, 12}; for(int i=0; i<b.length; ++i) { int p = rank(b[i], a); if(-1 == p) { System.out.println("failed to search " + b[i] + " : ( "); } else { //数组是有序的 System.out.println("the " + b[i] + " position is " + p + " : ) "); } } } }
the 4 position is 4 : ) failed to search 11 : ( the 5 position is 5 : ) failed to search 12 : (