• 数组元素的查找(折半查找)


    /*
         数组的查找 
         折半查找:前提是该数组是有序的数组
     */
    
    import java.util.Scanner;
    
    public class arrLookup{
        public static void main(String[] args){
            int[] arr = {1,4,6,8,34,56,78};
            System.out.println("Please enter the number you want to find:");
            Scanner in = new Scanner(System.in);
            int number = in.nextInt();
            
            //halfSearch
            int index = halfSearch(arr, number);
            System.out.println("index = "+index);
            //halfsearch_2
            int index_2 = halfSearch_2(arr, number);
            System.out.println("index_2 = "+index_2);
            
            //练习:将元素有序插入数组
            Scanner in_1 = new Scanner(System.in);
            int number_1 = in_1.nextInt();
            int index_3 = getIndex(arr, number_1);
            System.out.println("index_3 = "+index_3);
            
        
        }
        
        //折半查找
        public static int halfSearch(int[] arr, int key){
            int min = 0;
            int max = arr.length-1;
            int mid = (min+max)/2;
            //判断是否找到key
            while(key != arr[mid]){
                if(key > arr[mid])    //key大于中间值,把中间值后一个角标赋值给min,max不变
                    min = mid+1;
                else if(key < arr[mid])    //key小于中间值,把中间值前一个角标赋值给max,min不变
                    max = mid-1;
                
                if(min > max)    //如果min>max,说明该数组内没有key
                    return -1;    //该数组没有key
                
                mid = (min+max)/2;    //折半
            }
            return mid;    
        }
        
        //第二种折半查找
        public static int halfSearch_2(int[] arr, int key){
            int min = 0;
            int max = arr.length-1;
            int mid;
            //判断min是否小于等于max
            while(min <= max){
                mid = (min+max)>>1;
                if(key > arr[mid])
                    min = mid+1;
                else if(key < arr[mid])
                    max = mid-1;
                else if(key == arr[mid])    //找到key,返回角标
                    return mid;
            }
            return -1;
            
        }
        
        //练习:将元素有序插入数组
        public static int getIndex(int[] arr, int key){
            int min = 0;
            int mid;
            int max = arr.length-1;
            while(min <= max){
                mid = (min+max)>>1;
                if(key > arr[mid])
                    min = mid+1;
                else if(key < arr[mid])
                    max = mid-1;
                else if(key == arr[mid])
                    return min;
            }
            return min;
        }
    }
  • 相关阅读:
    学习笔记-级数
    闭包
    superfetch服务到底该不该关闭
    用tor进入“深网”
    浏览器内核
    媒体查询实现响应式布局
    oracle用浏览器界面管理数据库
    angular登录状态检查
    从输入网址后。。。。。。
    原型
  • 原文地址:https://www.cnblogs.com/rancvl/p/5277332.html
Copyright © 2020-2023  润新知