二分查找算法案例
  KRe60ogUm4le 2024年08月09日 61 0

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

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

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 来表示当前查找的区间范围,通过循环不断缩小区间,直到找到待查找元素或确定不存在为止。

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年08月09日 0

暂无评论

推荐阅读
  KRe60ogUm4le   2024年05月31日   63   0   0 pythonleetcode算法
  KRe60ogUm4le   2024年05月31日   126   0   0 leetcode算法
KRe60ogUm4le