Home Article Practice Java的二分查找法(含有中文注释 和 数字)

Java的二分查找法(含有中文注释 和 数字)

2023-04-06 23:04  views:996  source:小键人10618375    

import java.util.Scanner;
public class ErFenSearch{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
//二分查找
int []arr=new int[]{12,14,25,64,75,89,99,101}; //顺序数组
int desc=sc.nextInt();//输入要查找的数字;
int left=0,right=arr.length-1;
boolean loop=false;
//判断是否存在元素
while(left<=right){
int mid=(left+right)/2;//定义数组中间的下标:
if(desc>arr[mid]){
left=mid+1;//左边下标向右边移动
}else if(desc<arr[mid]){
right=mid-1;//右边下标向左边移动
}else if(desc==arr[mid]){//单找的数与中间值相同
System.out.println("存在:"+arr[mid]);
loop=true;
break;
}
}
if(loop==false){
System.out.println("不存在");
}
}
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)