Java之二分法

來源:互聯網
上載者:User

標籤:不能   min   color   java   bsp   表示   return   list   中間   

  1. 廢話不多說,先來程式.一步一步看注釋,

  2. 首先要注意:使用二分法時,數組必須是有序的,也就是從大到小或者從小到大的,不能是無序的

     1 public static int halfSearch(int[] arr,int key){ 2             int min,max,mid;//分別為最小值,最大值,和中間值 3             min = 0; 4             max = arr.length - 1; 5             mid = (max + min)/2;//這應該就是二分的核心了, 6             //當key = arr[mid]說明已經找到了這個資料,所以while迴圈的條件是!= 7             while(arr[mid] != key){ 8                 if(key > arr[mid]){ 9                     min = mid + 1;10                 }else if(key < arr[mid]){11                     max = mid - 1;12                 }13                 //返回-1表示沒有找到14                 if(max < min){15                     return -1;16                 }17                 mid = (max + min)/2;18             }19             //傳回值為對應key值得下標20             return mid;21         }    

     

     

 

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.