递归问题(三角数列 和 二分查找)

package javal.util.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *  数字序列  1,3,6,10,15,21
 * @author lh
 *
 */
public class SanjiaoNumber {

	/**
	 * @email 15688506227@163.com
	 */
	public static void main(String[] args) {
		try {
			System.out.println(inputNumber());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * @return
	 * @throws Exception
	 */
	public static int inputNumber() throws Exception {
		int input,output;
		InputStreamReader isr = new InputStreamReader(System.in);
		
		BufferedReader rd = new BufferedReader(isr);
		
		String str = rd.readLine();
		
		input =Integer.parseInt(str);
		
		output = triangle(input);
		
		return output;
	}
	
	/**
	 * @param n 第几项
	 * @return
	 */
	public static int triangle(int n) {
		if(n == 1) {
			return 1;
		}else {
			return n + triangle(n-1);
		}
	}
}

            递归就是方法调用自己,数字序列  1,3,6,10,15,21,28,这个数列中,第N项的值等于 (N-1)项加上N 的值。

            有序数组的递归二分查找:

package javal.util.test;

/**
 * 有序数组的二分查找递归方法
 * @author lh
 *
 */
public class BinaryFind {

	/**
	 * @email 15688506227@163.com
	 */
	private long[] array;
	public BinaryFind(long[] array) {
		this.array = array;
	}
	
	public int find(long tar) {
		return selffind(tar, 0, array.length-1);
	}
	/**
	 * 
	 * @param key        查找目标
	 * @param leftBound  数组开始 0
	 * @param rightBound 数组结束 len-1
	 * @return  下标
	 */
	public int selffind(long key, int leftBound, int rightBound) {
		int curIn=(leftBound + rightBound) / 2;
		
		if(array[curIn] == key) {
			return curIn;
		}else  if(leftBound > rightBound) {
			return -1;
		}else {
			if(array[curIn] < key) {
				return selffind(key, curIn+1, rightBound);
			}else {
				return selffind(key, leftBound, curIn -1);
			}
		}
		
	}
	
	public static void main(String[] args) {
		BinaryFind bclass = new BinaryFind(new long[] {1,2,45,55,668});
		System.out.println(bclass.find(55));
		System.out.println(bclass.find(1));
		System.out.println(bclass.find(85));
		System.out.println(bclass.find(668));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值