Java递归算法——二分查找
2024-09-23 23:21:11
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Random; //=================================================
// File Name : RecFind
//------------------------------------------------------------------------------
// Author : Common //类名:BinarySearch_Find
//属性:
//方法:
class Rec_Find{
private int[] temp;
private int searchKey;
//private int lowerBound = 0; //下界
//private int upperBound ; //上界
private int nElement; public int[] getTemp() {
return temp;
} public void setTemp(int[] temp) {
this.temp = temp;
} public Rec_Find(int[] temp) {//构造函数
this.temp = temp;
//this.upperBound = temp.length-1;
} public int find(int searchKey,int lowerBound,int upperBound){
int curNum;
this.searchKey = searchKey;
curNum = (lowerBound+upperBound)/2;
if(temp[curNum]==this.searchKey){
return curNum; //find
}
else if(lowerBound>upperBound){
return -1; //没有find
}
else{
if(temp[curNum]<this.searchKey){
return find(searchKey,curNum+1,upperBound);
}
else{
return find(searchKey,lowerBound,curNum-1);
}
} } } //类名:RandomArrays
//属性:
//方法:
class RandomArray{ //生成随机数组,有Num个 private int[] Arrays; public int[] getArrays(int Num){
// int[] Arrays = new int[Num];
Arrays = new int[Num];
Random r = new Random(); for(int i=0;i<Num;i++){
Arrays[i] = r.nextInt(1000);
// System.out.print(Arrays[i]+"、");
}
return Arrays;
}
} //类名:OrderedArrays
//属性:
//方法:
class OrderedArray{ //生成有序数组,从0开始到Num public int[] getArrays(int Num){
int[] Arrays = new int[Num]; for(int i=0;i<Num;i++){
Arrays[i] = i;
// System.out.print(Arrays[i]+"、");
}
return Arrays;
}
} //主类
//Function : RecFind
public class RecFind { public static void main(String[] args) {
// TODO 自动生成的方法存根 // RandomArrays array_demo = new RandomArrays();
// BinarySearch_Find arrays = new BinarySearch_Find(array_demo.getArrays(100)); OrderedArray array_demo = new OrderedArray();
Rec_Find arrays = new Rec_Find(array_demo.getArrays(100));
System.out.println(Arrays.toString(arrays.getTemp()));
System.out.println(arrays.find(55,0,100));
} }
最新文章
- ubuntu 安装Django MySQL
- session的常用方法。
- python 获取一个列表有多少连续列表
- Struts2学习笔记 - HelloWorld总结
- webapi输入验证过滤器ValidationActionFilter
- 函数类型+WINAPI+函数名(例如inline DWORD static WINAPI RecordToKeys(const DRWT&; theDRWT,WTSBH* pKey,DWORD dwMaxNum)
- 【推理,贪心】UVa 1319 - Maximum
- poj 1987 树的分治
- 在win7与XP系统下 C#缺省路径不同
- Jquery EasyUI修改行背景的两种方式
- UBUNTU如何改变mysql默认文件夹数据文件夹
- JavaScript(第二十一天)【DOM元素尺寸和位置】
- silverlight中 设置 头像(添加图片)
- windows生成当前目录树
- 警告!中国90%AI初创企业将在两年内落败出局
- Java设计模式之七 ----- 享元模式和代理模式
- Windows 下安装 swoole 具体步骤(php)
- unity3d-知识汇总
- Spring Advice
- Could not load file or assembly &#39;System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&#39; or one of its dependencies. The located assembly&#39;s manifest definition does not mat