二分查找算法案例

折半查找(二分查找)是一种常见且高效的查找算法,适用于有序数组。其基本思想是首先将数组按照中间位置折半,然后判断待查找元素与中间元素的大小关系,从而确定待查找元素在左半部分还是右半部分。通过不断折半和判断,最终找到待查找元素或确定其不存在。

以下是一个使用折半查找的示例代码:

java 复制代码
public class BinarySearch {
    public static int binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (array[mid] == target) {
                return mid;
            } else if (array[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return -1; // 表示未找到
    }
    
    public static void main(String[] args) {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int target = 6;
        
        int result = binarySearch(array, target);
        
        if (result != -1) {
            System.out.println("元素 " + target + " 的索引位置为 " + result);
        } else {
            System.out.println("元素 " + target + " 不存在于数组中");
        }
    }
}

以上代码中,binarySearch 方法接收一个有序数组 array 和待查找元素 target,并返回待查找元素在数组中的索引位置,如果不存在则返回 -1。算法使用了两个指针 leftright 来表示当前查找的区间范围,通过循环不断缩小区间,直到找到待查找元素或确定不存在为止。

需要注意的是,前提是数组必须是有序的。如果数组无序,可以在查找之前先对数组进行排序。

相关推荐
q***95221 天前
Tomcat下载,安装,配置终极版(2024)
java·tomcat
2***d8851 天前
详解tomcat中的jmx监控
java·tomcat
无敌最俊朗@1 天前
Qt事件循环队列剖析!!!
java
v***5651 天前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
做怪小疯子1 天前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵
努力学习的小廉1 天前
我爱学算法之—— BFS之最短路径问题
算法·宽度优先
python零基础入门小白1 天前
【万字长文】大模型应用开发:意图路由与查询重写设计模式(从入门到精通)
java·开发语言·设计模式·语言模型·架构·大模型应用开发·大模型学习
高山上有一只小老虎1 天前
构造A+B
java·算法
学困昇1 天前
C++中的异常
android·java·c++
木头左1 天前
缺失值插补策略比较线性回归vs.相邻填充在LSTM输入层的性能差异分析
算法·线性回归·lstm