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);
    }
}

原文地址:https://www.cnblogs.com/gailuo/p/4532831.html