如果要实现二分查找,那么被查找的数列一定是有序的。这里有对升序和降序数列的二分查找。
package exer;
import java.util.Scanner;
/**
* ClassName
* Description:
*
* 练习二分法查找
*
* Date 2022/5/5 22:08
*
* @User : TThh
* @since JDK 17.0
*/
public class BinarySearch {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arrNumber = new int[5];
System.out.println("请输入五个有序(升序或降序)的值:");
for (int i = 0; i < 5; i++) {
arrNumber[i] = in.nextInt();
}
System.out.println("请输入您要查找的值:");
int target = scan.nextInt();
int start = 0, end = arrNumber.length - 1;
//数列升序时
int middle;
if(arrNumber[start] < arrNumber[end] ) {
while (start <= end) {
middle = (start + end) / 2;
if (arrNumber[middle] < target) start = middle + 1;
if (arrNumber[middle] > target) end = middle;
if (arrNumber[middle] == target) {
System.out.println("目标元素的索引为 : " + middle);
return;
}
}
System.out.println("您输入的元素不存在!");
}else {//数列降序时
while (start <= end) {
middle = (start + end) / 2;
if (arrNumber[middle] < target) start = middle - 1;
if (arrNumber[middle] > target) end = middle + 1;
if (arrNumber[middle] == target) {
System.out.println("目标元素的索引为 : " + middle);
return;
}
}
System.out.println("您输入的元素不存在!");
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)