zoukankan      html  css  js  c++  java
  • Java 蹒跚自学之 第八日 数组 二分查找法

    找出一个值在一个数组中的位置

    class  toBinarysearch
    {
        // 找出一个数 在一个数组中的位置 
        public static int search(int[] arr,int key)
        {
            for (int x=0;x<arr.length ;x++ )
            {
                if (key==arr[x])
                {
                    return x;
                }
            }

            return -1;
        }

        //  找出一个数,在一个有序数组中的位置  

        public static int binarySearch(int[] arr, int key)
        {
            int min =0;
            int max =arr.length-1;
            int mid =(min+max)/2;

            while (min<max)
            {
                if (key>arr[mid])
                {
                    min=mid+1;
                    mid=(min+max)/2;
                }else if (key<arr[mid])
                {
                    max =mid-1;
                    mid=(min+max)/2;
                }else return mid;
            }
            return -1;
        }
        public static void main(String[] args)
        {
            int[] arr ={4,3,66,11,34,78,53};
            int[] arr1={2,4,6,8,9,12,45,78,99};
            // int index =search(arr,55);

            int index =binarySearch(arr1,66);
            System.out.println(index);
        }
    }

    数组应用   -------------查表法

     

    //实现将一个十进制整数  转换成其他常用进制  例如 二进制  八进制 十六进制

    /*分析 :任何数值在系统中都是以二进制形式存储的 。如果把一个二进制的数值转换成一个十六进制的数值 。那么就是对二进制的数 每四位 进行求和 再放到十六进制的相对应的位数上。

    */
    class JinZhi
    {
        public  static void zhuanHuan(int x,int base,int offset)
        {
            if (x==0)
            {
                System.out.println('0');
                return;

            }
            char [] chs = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
            char [] chsout=new char[32];
            int pos= chsout.length;
            while (x!=0)
            {
                chsout[--pos] =chs[x&base];
                   x=x>>>offset;
            }

            for (int w=pos;pos<chsout.length ;pos++ )
            {
                System.out.print(chsout[pos]);
            }

              System.out.println();
        }

        public static void toHex(int num)
        {
            zhuanHuan(num,15,4);
        }
        public static void toBinary(int num)
        {
            zhuanHuan(num,1,1);
        }

        public static void toOctal(int num)
        {
            zhuanHuan(num,7,3);
        }
        public static void main(String[] args)
        {
            toHex(0);
            toBinary(6);
            toOctal(60);
        }
    }

  • 相关阅读:
    js获取当前网页的源码
    jquery实现点击图片全屏查看功能
    html查看大图、js查看大图
    【后端】SSM(Spring + SpringMVC + Mybatis)框架整合(二)
    【macOS】免费使用正版 Paragon NTFS for Mac(非破解)
    【后端】SSM(Spring + SpringMVC + Mybatis)框架整合(一)
    c# 自动生成N个随机数和为1
    分布式事务的解决方案
    【JUC】一些线程基础
    【工具】apng图像判定调研
  • 原文地址:https://www.cnblogs.com/gailuo/p/4532831.html
Copyright © 2011-2022 走看看