📜  Java中的二分查找

📅  最后修改于: 2022-05-13 01:54:34.164000             🧑  作者: Mango

Java中的二分查找

二进制搜索是对输入进行排序时应用的搜索技术之一,因为这里我们关注的是找到充当参考框架的中间元素,因为元素已经排序,所以无论是向左还是向右。这种搜索有助于优化搜索技术,每次迭代都被称为二分搜索,读者会强调它,因为它间接应用于解决问题。现在你一定在想,如果输入没有排序,那么结果是不确定的。

现在让我们坚持两个函数返回的负值的显着值

该函数返回搜索键的索引,如果它包含在数组中;否则,(-(插入点)- 1)。插入点定义为将键插入数组的点:第一个元素的索引大于键,或者如果数组中的所有元素都小于指定的键,则为 a.length。请注意,这保证了当且仅当找到键时,返回值将 >= 0。

Java中二分查找的实现

Java
// Java implementation of recursive Binary Search
class BinarySearch
{
    // Returns index of x if it is present in arr[l..
    // r], else return -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r>=l)
        {
            int mid = l + (r - l)/2;
  
            // If the element is present at the
            // middle itself
            if (arr[mid] == x)
               return mid;
  
            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > x)
               return binarySearch(arr, l, mid-1, x);
  
            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid+1, r, x);
        }
  
        // We reach here when element is not present
        //  in array
        return -1;
    }
  
    // Driver method to test above
    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);
    }
}


Java
// Java Program to demonstrate working of binarySearch()
// Method of Arrays class In a sorted array
 
// Importing required classes
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring an integer array
        int arr[] = { 10, 20, 15, 22, 35 };
 
        // Sorting the above array
        // using sort() method od Arrays class
        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");
    }
}


Java
// Java Program to Demonstrate Working of binarySearch()
// method of Collections class
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of integer type
        List al = new ArrayList();
 
        // Populating the Arraylist
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(10);
        al.add(20);
 
        // 10 is present at index 3
        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");
    }
}


输出:
Element found at index 3

Java中的二分查找类型

在Java中进行二分查找有两种方法

  • Arrays.binarysearch
  • Collections.binarysearch

类型 1: Arrays.binarysearch()

它也适用于可以是原始数据类型的数组。

例子:

Java

// Java Program to demonstrate working of binarySearch()
// Method of Arrays class In a sorted array
 
// Importing required classes
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring an integer array
        int arr[] = { 10, 20, 15, 22, 35 };
 
        // Sorting the above array
        // using sort() method od Arrays class
        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 = 3
40 Not found

现在让我们看看 Collections.binarySearch() 如何为 LinkedList 工作。所以基本上如上所述,对于像 ArrayList 这样的“随机访问”列表,该方法在 log(n) 时间内运行。如果指定的列表没有实现 RandomAccess 接口并且很大,则此方法将执行基于迭代器的二进制搜索,执行 O(n) 链接遍历和 O(log n) 元素比较。

类型 2: Collections.binarysearch()

它适用于像 ArrayList 和 LinkedList 这样的对象集合。

例子

Java

// Java Program to Demonstrate Working of binarySearch()
// method of Collections class
 
// Importing required classes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of integer type
        List al = new ArrayList();
 
        // Populating the Arraylist
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(10);
        al.add(20);
 
        // 10 is present at index 3
        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 = 3
15 Not found