Algorithms - 递归(recursion) 详解 及 代码

递归(recursion) 详解 及 代码

 

本文地址: 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 : ( 

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SpikeKing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值