JAVA Arrays.binarySearch

來源:互聯網
上載者:User

標籤:

轉自:http://blog.csdn.net/somebodydie/article/details/8229343

  1. package com.jaky;  
  2. import java.util.*;  
  3. public class Quest {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         // TODO Auto-generated method stub  
  10.         String[] colors = {"blue","red","green","yellow","orange","black"};  
  11.           
  12.         Arrays.sort(colors);  
  13.           
  14.         int s2=Arrays.binarySearch(colors, "orange");  
  15.         int s3=Arrays.binarySearch(colors, "violet");  
  16.           
  17.         System.out.println(s2+""+s3);  
  18.     }  
  19.   
  20. }  

輸出結果為:

3-6

violet在 colors數組中不存在,一直很納悶為什麼s3會等於 -6 

查看JDK API 才知道:

 

binarySearch
public static int binarySearch(byte[] a,                               byte key)
使用二分搜尋法來搜尋指定的 byte 型數組,以獲得指定的值。必須在進行此調用之前對數組進行排序(通過  sort(byte[]) 方法)。如果沒有對數組進行排序,則結果是不確定的。如果數組包含多個帶有指定值的元素,則無法保證找到的是哪一個。
參數:
a - 要搜尋的數組
key - 要搜尋的值
返回:
如果它包含在數組中,則返回搜尋鍵的索引;否則返回 (-( 插入點) - 1)。 插入點 被定義為將鍵插入數組的那一點:即第一個大於此鍵的元素索引,如果數組中的所有元素都小於指定的鍵,則為 a.length。注意,這保證了若且唯若此鍵被找到時,返回的值將 >= 0。
當找不到要搜尋的值時,返回 (-( 插入點) - 1),雖然不知道怎麼理解這個插入點,但是經過多次測試的結果表明,好像就是得到搜尋數組的長度的負值。

JAVA Arrays.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.