java实现二分法(递归、非递归)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36146261/article/details/79975364

package  arithmetic ;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.sound.midi.MidiChannel;


public class Test{
public static void main(String[] args) {
int[] arrs = new int[10];
for (int i = 0; i < arrs.length; i++) {
arrs[i]=i;
}
System.out.println(serNumber(arrs, 4 , 0, arrs.length-1));
System.out.println(serachNumber(arrs,7));

}

//传如数组和要查找的数字
public static Object serachNumber(int[] arrs,int serNum){
if (arrs == null)
return null;

int start =0;
int end = arrs.length-1;
int mid =0;
while(start<=end){
mid = (start+end )/2;
//与中间值比较确定在左边还是右边区间,以调整区域 
if(serNum<arrs[mid]){
end = mid-1;
}else if(serNum>arrs[mid]){
start= mid +1;
}else {
return "存在";
}
}
return "没找到";
}

public static int serNumber(int[] arrs,int num ,int begin,int end){
if(arrs ==null || begin > end || num< begin ||num>end){
return -1;
}
int mid = (begin+end)/2;
if(arrs[mid]<num){
return serNumber(arrs, num , mid, end);
}else if (arrs[mid]>num){
return serNumber(arrs, num , begin, mid);
}else{
return mid;
}
}
}
阅读更多

没有更多推荐了,返回首页