本文介绍了有人可以向我解释这个java程序的算法吗?每个代码的使用?我很难理解这一点。非常感谢 :)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
我的尝试:
我在网上找到了它,我想知道它的算法的解释。
What I have tried:
I found it in the net and I want to know the explanation of it's algorithm.
推荐答案
这篇关于有人可以向我解释这个java程序的算法吗?每个代码的使用?我很难理解这一点。非常感谢 :)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!