- public class Test2T2Method {
- /**
- * 采用二分法查找顺序排列数组里的一个数。
- */
- public static void main(String[] args) {
- int[] array ={1,2,3,4,5,6,7,8,9};
- int n=6;
- System.out.println(twoFind(array,n));
- }
- public static int twoFind(int[] array,int n){
- int startPos=0;//初始起点位置
- int endPos=array.length-1;//初始结束位置
- int index=(startPos+endPos)/2;//取中点
- while(startPos<=endPos){
- if (array.length==0){return -1;}//空数组无效
- if (n==array[index]){return index;}
- if (n>array[index]){
- //调整起点位置
- startPos=index+1;
- }
- if (n<array[index]){
- //调整结束位置
- endPos=index-1;
- }
- index=(startPos+endPos)/2;
- }
- return -1;
- }
- }
之前写成这样,当查找6的时候造成死循环,差点把系统整死.
- public class Test2T2Method {
- /**
- * 采用二分法查找顺序排列数组里的一个数。
- */
- public static void main(String[] args) {
- int[] array ={1,2,3,4,5,6,7,8,9};
- int length=array.length;
- int times=0;
- int n=6;
- int index=length/2;
- boolean Found=false;
- while(!Found){
- if(n==array[index]){
- Found=true ;
- }
- if(n>array[index]){
- index=(index+length)/2;
- }
- if(n<array[index]){
- index=index/2;
- }
- times++;
- }
- System.out.println(index);
- System.out.println("查找这个数需循环 "+times+" 次");
- }
- }

本文详细介绍了二分查找算法的实现方法,并通过两个具体的Java代码示例对比了正确的实现方式与容易导致错误的方式,帮助读者深入理解二分查找的工作原理及其在实际应用中的注意事项。
2970

被折叠的 条评论
为什么被折叠?



