您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java如何实现二进制搜索?

2024/3/9 12:20:49发布25次查看
在java中有两种方法可以进行二进制搜索。
1.arrays.binarysearch()适用于也可以是原始数据类型的数组。
import java.util.arrays; public class gfg { public static void main(string[] args) { int arr[] = { 10, 20, 15, 22, 35 }; arrays.sort(arr); int key = 22; int res = arrays.binarysearch(arr, key); if (res >= 0) system.out.println(key + " found at index = " + res); else system.out.println(key + " not found"); key = 40; res = arrays.binarysearch(arr, key); if (res >= 0) system.out.println(key + " found at index = " + res); else system.out.println(key + " not found"); } }
输出:
22 found at index = 340 not found
2.collections.binarysearch()适用于对象集合,如arraylist和linkedlist。
import java.util.list; import java.util.arraylist; import java.util.collections; public class gfg { public static void main(string[] args) { list<integer> al = new arraylist<integer>(); al.add(1); al.add(2); al.add(3); al.add(10); al.add(20); int key = 10; int res = collections.binarysearch(al, key); if (res >= 0) system.out.println(key + " found at index = " + res); else system.out.println(key + " not found"); key = 15; res = collections.binarysearch(al, key); if (res >= 0) system.out.println(key + " found at index = " + res); else system.out.println(key + " not found"); } }
输出:
10 found at index = 315 not found
如果输入没有排序怎么办?
如果未对输入列表进行排序,则结果未定义。
如果有重复怎么办?
如果有重复,则无法保证找到哪一个。
collections.binarysearch如何为linkedlist工作?
此方法在log(n)时间内运行,用于“随机访问”列表,如arraylist。如果指定的列表没有实现randomaccess接口并且很大,则此方法将执行基于迭代器的二进制搜索,该搜索执行o(n)链接遍历和o(log n)元素比较。
两个函数返回的负值的重要值是多少?
该函数返回搜索键的索引(如果它包含在数组中); 否则,( - (插入点) - 1)。插入点定义为键将插入到数组中的点:第一个元素的索引大于键,或者如果数组中的所有元素都小于指定键,则为a.length。请注意,当且仅当找到密钥时,这可以保证返回值> = 0。
如何在java中实现我们自己的二进制搜索?
class binarysearch { int binarysearch(int arr[], int l, int r, int x) { if (r>=l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarysearch(arr, l, mid-1, x); return binarysearch(arr, mid+1, r, x); } return -1; } public static void main(string args[]) { binarysearch ob = new binarysearch(); int arr[] = {2,3,4,10,40}; int n = arr.length; int x = 10; int result = ob.binarysearch(arr,0,n-1,x); if (result == -1) system.out.println("element not present"); else system.out.println("element found at index " + result); } }
输出:
element found at index 3
相关推荐:《java教程》
本篇文章就是关于java实现二进制搜索的方法介绍,希望对需要的朋友有所帮助!
以上就是java如何实现二进制搜索?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product