📄 binarysearch.java
字号:
//BinarySearch.java 比较数组元素值的大小
public class BinarySearch
{
public static void main(String args[])
{
int i, mid, low, high, midvalue, key;
boolean flag;
low=0;
key=21;
int a[] = {5, 13, 19, 21, 37, 56, 64, 75, 80, 88, 92}; //声明数组a,并赋初值
high=a.length-1;
flag=true;
while(flag){
flag=false;
mid=(low+high)/2;
midvalue=a[mid];
if(low==high){
if(key==midvalue){
System.out.println("Find the key! The index of the key " + key + " is: " + mid);
}
else{
System.out.println("Can not find the key " + key + " !");
}
flag=false;
break;
}
if(key==midvalue){
System.out.println("Find the key! The index of the key " + key + " is: " + mid);
flag=false;
break;
}
else if(key<midvalue){
high=mid-1;
flag=true;
}
else{
low=mid+1;
flag=true;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -