首页 > 其他 > 详细

二分查找法

时间:2019-05-04 19:14:40      阅读:99      评论:0      收藏:0      [点我收藏+]
package com.nxz.testboot.otherTest;

/**
 * 二分查找
 */
public class BinarySearch {


    /**
     * @param arr    目标数组
     * @param n      数组大小
     * @param target 要查找的目标值
     * @return 存在目标值则返回目标值索引,没有则返回-1
     */
    public static int binarySearch(int[] arr, int n, int target) {
        int l = 0, r = n - 1; // 定义边界  [l....r]
        while (l <= r) { //左边界小于等于右边界
       //l + r 可能越界, 修改为 l + (r - l)/2
       int mid = (l + r) / 2; //中间值 int mid = l + (r - l) / 2;
if (arr[mid] == target) {//中间值等于目标值时返回索引值 return mid; } if (arr[mid] < target) { l = mid + 1; } else { r = mid - 1; } } return -1; } public static void main(String[] args) { long startTime = System.currentTimeMillis(); int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 46, 60}; int i = binarySearch(arr, 10, 6); System.out.println(i); long endTime = System.currentTimeMillis(); System.out.println(endTime - startTime); } }

 

二分查找法

原文:https://www.cnblogs.com/nxzblogs/p/10552441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!