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

    /**
     * 
     * @author Administrator
     * 功能:二分查找
     */
    package com.test1;
    
    public class Demo5_4 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int arr[] = { 2, 5, 7, 12, 25 };
            BinaryFind bf = new BinaryFind();
            bf.find(0, arr.length-1, 12, arr);
        }
    }
    
    class BinaryFind {
        public void find(int leftIndex, int rightIndex, int val, int[] arr) {
            // 首先找打中间的数
            int midIndex = (leftIndex + rightIndex) / 2;
            int midVal = arr[midIndex];
    
            if (rightIndex >= leftIndex) {
    
                // 如果要找的数比midVal大
                if (midVal > val) {
                    // 在arr数组的左边数中找
                    find(leftIndex, midIndex - 1, val, arr);
                } else if (midVal < val) {
                    // 在arr的右边的数去找
                    find(midIndex + 1, rightIndex, val, arr);
                } else if (midVal == val) {
                    System.out.println("找到下标" + midIndex);
                }
            }
    
        }
    }
  • 相关阅读:
    UVA 1001 Say Cheese
    UVa 821 Page Hopping
    UVA 1569 Multiple
    UVA 1395 Slim Span
    UVA 12219 Common Subexpression Elimination
    UVA 246 10-20-30
    Mysql基本操作
    浅析关键字static
    面试回答技巧
    五个程序员好习惯
  • 原文地址:https://www.cnblogs.com/beautiful-code/p/5344567.html
Copyright © 2011-2022 走看看