Java 數組 之 一維數組 折半尋找 BinarySearch

來源:互聯網
上載者:User

標籤:void   util   string   位置   http   find   數組   java   二分   

http://www.verejava.com/?id=16992676834929

/*用二分法: 從一個已經排好序的數組scores中尋找給定的值 value 的索引位置思路:      1. 先初始化最低位 low=0, 最高位high=scores.length-1    2. 求出中間位 mid=(low+high)/2 的值 scores[mid]    3. 將中間位scores[mid]與value比較          如果scores[mid]==value 說明找到了列印當前索引mid,         如果scores[mid]<value 說明要找的value值 在mid+1到 high 之間        如果scores[mid]>value 說明要找的value值 在low 到 mid-1 之間    4. 依此類推 迴圈執行 3的步驟直到找到 value 或者 沒有找到 low>=high 終止迴圈*/import java.util.Scanner;public class ArrayBinarySearch{    public static void main(String[] args)    {        //定義一個已經排好序的分數數組        int[] scores={30,40,50,70,85,90,100};        System.out.println("請輸入要尋找的值value :");        Scanner in=new Scanner(System.in);        int value=in.nextInt();        //1. 先初始化最低位 low=0, 最高位high=scores.length-1        int low=0;        int high=scores.length-1;        int mid=0;        boolean isFind=false;        while(low<high)        {            //2. 求出中間位 mid=(low+high)/2 的值 scores[mid]            mid=(low+high)/2;            //3. 將中間位scores[mid]與value比較              //如果scores[mid]==value 說明找到了列印當前索引mid,             if(scores[mid]==value)            {                System.out.println("找到value:"+value+" 在數組的索引位置為:"+mid);                isFind=true;                break;            }            //如果scores[mid]<value 說明要找的value值 在mid+1到 high 之間            if(scores[mid]<value)            {                low=mid+1;            }            //如果scores[mid]>value 說明要找的value值 在low 到 mid-1 之間            if(scores[mid]>value)            {                high=mid-1;            }        }        if(!isFind)        {            System.out.println("在數組中沒有找到值");        }    }}

http://www.verejava.com/?id=16992676834929

Java 數組 之 一維數組 折半尋找 BinarySearch

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.