zoukankan      html  css  js  c++  java
  • 二分查找法

    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); } }
  • 相关阅读:
    Bootstrap导航条
    Bootstrap导航
    Bootstrap输入框组
    Bootstrap按钮式下拉菜单
    Bootstrap按钮组
    Bootstrap下拉菜单
    Bootstrap辅助类
    Bootstrap栅格系统
    Bootstrap学习目录
    Bootstrap图标
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/10552441.html
Copyright © 2011-2022 走看看