• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Aspiring
博客园    首页    新随笔    联系   管理    订阅  订阅

003—二分查找的实现

package oo3_binary_search;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author ALazy_cat 
 *     二分查找:要求待查表有序。二分查找的基本思想是将n个元素分成大致相等的两部分,取 a[n/2]与x做比较,
 * 如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则
 * 只要在数组a的右半部搜索x.
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] a = { 0, 10, 19, 24, 73, 94, 95 };
        int pos = 0;
        System.out.println("数组: " + Arrays.toString(a));
        Scanner in = new Scanner(System.in);
        System.out.print("请输入关键字: ");
        int key = in.nextInt();
        in.close();
        System.out.println("在数组中搜索数字 " + key + "...");
        if ((pos = binarySearch1(a, key)) != -1) {
            System.out.println(key + " 在数组中的位置是: " + pos);
        } else {
            System.out.println(key + "不存在.");
        }
        System.out.println("---------------------");
        System.out.println("在数组中搜索数字 " + key + "...");
        if ((pos = binarySearch2(a, key)) != -1) {
            System.out.println(key + " 在数组中的位置是: " + pos);
        } else {
            System.out.println(key + "不存在.");
        }
    }

    // 二分查找的递归实现
    // 如果在有序表中有满足a[i] == key的元素存在,则返回该元素的索引i;否则返回-1
    public static int binarySearch1(int[] a, int key) {
        return binarySearch1(a, key, 0, a.length - 1);
    }

    public static int binarySearch1(int[] a, int key, int low, int high) {
        if (low > high)
            return -1;
        int mid = (low + high) / 2;
        if (a[mid] == key) {
            return mid;
        } else if (a[mid] < key) {
            return binarySearch1(a, key, mid + 1, high);
        } else {
            return binarySearch1(a, key, low, mid - 1);
        }
    }

    // 二分查找的循环实现
    // 循环条件:low<=high;
    // 循环体:改变low与high的值即可
    public static int binarySearch2(int[] a, int key) {
        int low = 0;
        int high = a.length - 1;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            if (a[mid] == key) {
                return mid;
            } else if (a[mid] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}

 

posted @ 2017-12-21 14:46  Aspiring  阅读(108)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3