本文使用Java实现了一个对数组的二分查找算法,首先使用泛型数组列表构建了待查找数组,然后使用冒泡排序方法对这一数组进行了排序并输出,最后使用二分查找算法依照key值进行搜索,输出key值在数组中的序号(序号从1开始)。本程序使用Java™ SE Runtime Environment (build 12.0.2+10),编译器使用IntelliJ IDEA。本程序由两个文件构成,Bi.Find.java构建了这一个类,Bi_FindTest.java对算法进行了测试。
Bi_Find.java源码如下:
package Bi_FindData;
import java.util.ArrayList;
import java.util.Scanner;
public class Bi_Find {
private ArrayList<Integer> array = new ArrayList<>();
public Bi_Find() {
String input;
do {
Scanner in = new Scanner(System.in);
array.add(in.nextInt());
System.out.println("Array input finished? press N and enter to continue...");
input = in.next();
} while (input.equals("N"));
}
public void BubbleSort()
{
int temp = 0;
for(int i = 0;i< array.size();i++)
{
for(int j = 0;j < array.size()-i-1;j++)
{
if(array.get(j)>array.get(j+1))
{
temp = array.get(j+1);
array.set(j+1,array.get(j));
array.set(j,temp);
}
}
}
System.out.println(array.toString());
}
public int Bi_FindNumber(int key)
{
int l = 0;
int h = array.size()-1;
while( l <= h )
{
int mid = (h+l)/2;
if(key<array.get(mid))
{
h = mid - 1;
System.out.println("key is smaller than mid number,and set higher number to " + h);
}
else if(key>array.get(mid))
{
l = mid + 1;
System.out.println("key is larger than mid number,and set lower number to " + l);
}
else
{
System.out.println("key is equal to mid number,and result is " + (mid+1));
break;
}
}
return 0;
}
}
Bi_FindTest.java源码如下:
package Bi_FindData;
public class Bi_findTest {
public static void main(String[] args)
{
Bi_Find bi_find = new Bi_Find();
bi_find.BubbleSort();
bi_find.Bi_FindNumber(5);
}
}
运行结果如下:
/Library/Java/JavaVirtualMachines/jdk-12.0.2.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=60150:/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Users/liangqian/IdeaProjects/二分查找/out/production/二分查找 Bi_FindData.Bi_findTest
1
Array input finished? press N and enter to continue...
N
2
Array input finished? press N and enter to continue...
N
3
Array input finished? press N and enter to continue...
N
4
Array input finished? press N and enter to continue...
N
6
Array input finished? press N and enter to continue...
N
5
Array input finished? press N and enter to continue...
y
[1, 2, 3, 4, 5, 6]
key is larger than mid number,and set lower number to 3
key is equal to mid number,and result is 5
Process finished with exit code 0
全文完。
如果您想了解更多C++/Java/机器学习相关的知识,欢迎扫描下方的二维码,关注“梁公子的备忘录”,每天一篇相关的技术分享,期待与您一起学习,共同进步!