欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

二分查找算法

最编程 2024-07-20 15:36:30
...

二分查找算法是一种在有序数组中查找特定元素的搜索算法。查找过程从数组的中间元素开始,如果中间元素正好是目标值,则查找过程结束;如果目标值大于或小于中间元素,则在数组大于或小于中间元素的那一半中查找,而不是整个数组。以下是一个二分查找的Java实现:

java

public class BinarySearch {  
    // Returns index of x if it is present in arr[], else return -1  
    int binarySearch(int arr[], int x) {  
        int l = 0, r = arr.length - 1;  
        while (l <= r) {  
            int m = l + (r - l) / 2;  
  
            // Check if x is present at mid  
            if (arr[m] == x)  
                return m;  
  
            // If x greater, ignore left half  
            if (arr[m] < x)  
                l = m + 1;  
  
            // If x is smaller, ignore right half  
            else  
                r = m - 1;  
        }  
  
        // if we reach here, then element was not present  
        return -1;  
    }  
  
    // Driver method to test above  
    public static void main(String args[]) {  
        BinarySearch bs = new BinarySearch();  
        int arr[] = {2, 3, 4, 10, 40};  
        int n = arr.length;  
        int x = 10;  
        int result = bs.binarySearch(arr, x);  
        if (result == -1)  
            System.out.println("Element not present in array");  
        else  
            System.out.println("Element found at index " + result);  
    }  
}

这段代码首先初始化一个指向数组最左边和最右边的指针(l和r)。然后,它进入一个循环,在循环中,它会计算中间索引(m),检查该索引处的值是否等于x。如果等于,就返回该索引。否则,如果x大于中间值,就在右半部分继续查找;如果x小于中间值,就在左半部分查找。如果在整个数组中都找不到x,就返回-1。