在这里,我们将解释如何编写一个 Java 程序来执行二分查找。
二分查找是在排序数组上实现的。列表应按升序排序。二分查找的逻辑是,检查关键元素是否小于中间元素。如果为真,则我们将丢弃 middle+1 到 limit 部分,并继续从 1 到 middle-1 元素进行搜索。如果关键元素 = 中间元素,则我们将显示在中间位置找到该元素。
首先,我们必须声明类 BinarySearch。声明整数变量 i、limit、key、first、last、middle。创建一个 Scanner 类的对象,命名为 sc。将数组元素的限制读取为 limit。声明一个大小为 limit 的整数数组。使用 for 循环将数组元素读入 array[i]。将搜索元素读入 key。然后设置 first=0、last=limit-1、middle=(first+last)/2。然后使用 while 循环检查 array[middle] 是否小于 key,如果中间元素小于关键元素,则我们将继续从 middle + 1 到 last 进行搜索。否则,我们继续从 first 到 middle -1 进行搜索。如果 array[middle]=key,则显示在 middle+1 位置找到该元素。如果 first > last,则显示未找到 key。
步骤 1:声明具有 public 修饰符的类 BinarySearch。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤 3:声明整数变量 i、limit、key、first、last、middle。
步骤 4:将数组的限制读入变量 limit。
步骤 5:声明一个大小为 limit 的数组。
步骤 6:使用 for 循环将元素读入数组。
步骤 7:将要搜索的元素读入变量 key。
步骤 8:设置 flag=0,last=limit-1,计算 middle 为 (first+last)/2。
步骤 9:使用 while 循环,条件为 first <= last,执行步骤 10。
步骤 10:检查 if array[middle] < key,然后设置 first = middle + 1。
步骤 11:否则,检查 if array[middle]==key,然后显示在 middle + 1 位置找到关键元素。
步骤 12:否则设置 last = middle - 1。
步骤 13:计算 middle=(first+last)/2 并重复步骤 9。
步骤 14:如果 first > last,则显示未找到 key。
import java.util.Scanner;
public class BinarySerach{
public static void main(String args[]){
int i, limit,key,first, last, middle;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit of numbers:");
limit = sc.nextInt();
int array[] = new int[limit];
System.out.println("Enter " + limit + " numbers");
for (i= 0; i < limit; i++)
array[i] = sc.nextInt();
System.out.println("Enter the search element:");
key= sc.nextInt();
first = 0;
last = limit - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < key )
first = middle + 1;
else if ( array[middle] == key )
{
System.out.println("The key element "+key +" found at location "+(middle+1));
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(key + " is not found.\n");
}
}
Enter the limit of numbers:5 Enter 5 numbers: 2 6 8 10 12 Enter the search element:12 The key element 12 found at location 5