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

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Scanner;
    
    public class BinarySearch {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            ArrayList<Integer> arrayList = new ArrayList<>();
            System.out.println("输入添加数字的个数:");
            int n = sc.nextInt();
    
            for (int i = 0; i < n; i++) {
                arrayList.add(sc.nextInt());
            }
            System.out.println("当前列表:"+arrayList);
           /* for (int i = 0; i < arrayList.size(); i++) {
                Collections.sort(arrayList);
            }
            System.out.println("排序后:"+arrayList);*/
            System.out.println("输入要查找的数字:");
            int num=sc.nextInt();
    
    
            found(arrayList, num);
    
        }
        public static void found(ArrayList<Integer> str, int item){
            int low = 0;
            int high = str.size()-1;
            int guss=0;
            while (low <= high) {
                int mid = (low + high) / 2;
                guss = str.get(mid);
                if (guss == item) {
                    System.out.println("找到了所找数字: "+guss+" 且在第"+(mid+1)+"个位置");
                    break;
                }
                if (guss > item) {
                    high = mid - 1;
                }else {
                    low = mid + 1;
                }
            }
            if (guss!=item) {
                System.out.println("None");
            }
    
        }
    }
    
  • 相关阅读:
    pionter指针小结
    C++笔记 5
    C++笔记 3
    ipad safari 滚动(overflow)解决方案
    IE9 BUG overflow :auto 底部空白解决方案
    asp.net 导出EXCEL超高兼容(不用装Excel)
    jquery post 同步异步总结
    jquery-alert对话框
    左固定右边自适应框架
    删除Cookies
  • 原文地址:https://www.cnblogs.com/saysayzhou/p/14505647.html
Copyright © 2011-2022 走看看