Java 蹣跚自學之 第八日 數組 二分尋找法

來源:互聯網
上載者:User

標籤:

找出一個值在一個數組中的位置

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

Java 蹣跚自學之 第八日 數組 二分尋找法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.