折半查找有点绕,多看看
掌握知识点- Scanner与数组的灵活运用
- 折半查找法
- 顺序查找法
import java.util.Scanner;
public class FindTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[(sc.nextInt())]; //用户控制数组长度
int n = sc.nextInt(); //需要查找的数值
for (int i = 0; i < arr.length; i++){ //数组赋值
arr[i] = sc.nextInt();
}
//******************折半查找******************************************
int min=0;
int mid;
int count=0;
// 查找给定元素索引,并输出查找次数
int max=arr.length-1; //数组索引值
mid=(max+min)/2; //数组索引二分
while(true){
count++;
if (n < arr[mid]){
max = mid - 1;
}else if(n > arr[mid]){
min = mid + 1;
}else{
System.out.println("索引值:" + mid + "。查找次数:" + count +"。");
break;
}
if(max < min){
System.out.println("没有找到");
break;
}
mid = (max + min) / 2;
}
}
}
编程要求
仔细阅读右侧编辑区内给出的代码框架及注释,在 Begin-End 间编写程序代码,使用折半方法查找数组中某元素的索引,并统计出查找次数,具体要求如下:
接收给定的数据(如:4 88 43 43 98 #…,其中第一个数代表数组长度,第二个数代表需要查找的元素,其余数代表数组元素,# 号用于终止接收数据),遇到 # 号终止接收;
创建数组,使用折半方法查找数组中某元素的索引,并统计出查找次数。
注意:数字分隔符为空格。



