用JAVA写一个完整的折半查找法!!!

一定要用JAVA写 C,C++滚蛋!!
2025-03-09 22:06:19
推荐回答(2个)
回答1:

import java.util.Scanner;

public class b {

/**
*
*   *折半查找法,又称十分法查找 查找的对象是一个按序排好的数组   
*/

public static void main(String[] args) {

int[] initVals = { 9, 12, 37, 53, 67, 71, 89, 122, 290, 435, 555, 888,
1104, 1111, 2222, 3333, 21343, 43256, 56778300 };

for (int i = 0; i < initVals.length; i++)

{

System.out.print(initVals[i] + "、");

}

Scanner cin = new Scanner(System.in);

while (cin.hasNext())

{
int targetVal = cin.nextInt();

b bq = new b();

int postion = bq.query(initVals, targetVal);

if (postion == -1)
System.out.println("没有找到");

else
System.out.println("要查找的数字在数组中的第 " + (postion + 1) + "个位置");
}
}

/*
*
* 29 29 * @param values 要找的数组对象
*
* 30 30 * @param targetVal 要找的目标数字
*
* 31 31 * @return -1 没有找到,返回-1
*
* 32 32
*/

public int query(int[] initVals, int targetVal) {

int lowBound = 0;
int upBound = initVals.length - 1;

// 相当于一个指针,指向下一个要比的数字

int nowPostion;

while (true) {

// 指向现在所有数字的中间,没有整除时向下取整,如7/2=3

nowPostion = (lowBound + upBound) / 2;

// 如果现在这个数字就是了,返回现在的编号

if (initVals[nowPostion] == targetVal) {

return nowPostion;

}

// 如果上界小于下界时,说明已经找完全部了,返回-1表示没有找到

else if (lowBound > upBound) {

return -1;

}

// 还可以继续找
else {

// 当前指针的数比targetVal要小,那么要往小的方向继续找

if (initVals[nowPostion] < targetVal) {

lowBound = nowPostion + 1;

}

// 当前指针的数比targetVal要大,那么要往大的方向继续找

else {

upBound = nowPostion - 1;
}

}
}

}

}

回答2:

@Override
public int search(int[] a, int a1) {
int min = 0;
int max = a.length;
int mid = (min+max)/2;
while(a[mid]!=a1){
if(a[mid]>a1){
max = mid;
}else{
min = mid;
}
mid = (min+max)/2;
}
if(min>max){
return -1;
}
return mid;
}