關於java的binarySearch()方法

來源:互聯網
上載者:User

標籤:index   種類型   二分   arch   無法   rgs   baidu   class   targe   

binarySearch()方法提供了多種重載形式,用於滿足各種類型數組的尋找需要,binarySearch()有兩種參數類型

註:此法為二分搜尋法,故查詢前需要用sort()方法將數組排序,如果數組沒有排序,則結果是不確定的,另外
如果數組中含有多個指定值的元素,則無法保證找到的是哪一個。
⑴.binarySearch(object[ ], object key);
如果key在數組中,則返回搜尋值的索引;否則返回-1或者"-"(插入點)。插入點是索引鍵將要插入數組的那一點,即第一個大於該鍵的元素索引。
eg:

package Number;
import java.util.Arrays;
public class IntFunction
{
public static void main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarySearch(a, 5);
int x2 = Arrays.binarySearch(a, 4);
int x3 = Arrays.binarySearch(a, 0);
int x4 = Arrays.binarySearch(a, 10);
System.out.println("x1:" + x1 + ", x2:" + x2);
System.out.println("x3:" + x3 + ", x4:" + x4);
}
}
/*輸出結果:
x1:-4, x2:2
x3:-1, x4:-7
*/

1.不存在時由1開始計數;

2.存在時由0開始計數。
⑵.binarySearch(object[ ], int fromIndex, int endIndex, object key);
如果要搜尋的元素key在指定的範圍內,則返回搜尋鍵的索引;否則返回-1或者"-"(插入點)。
eg:
1.該搜尋鍵在範圍內,但不在數組中,由1開始計數;
2.該搜尋鍵在範圍內,且在數組中,由0開始計數;
3.該搜尋鍵不在範圍內,且小於範圍內元素,由1開始計數;
4.該搜尋鍵不在範圍內,且大於範圍內元素,返回-(endIndex + 1);(特列)
eg:
package Number;
import java.util.Arrays;
public class IntFunction
{
public static void main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarySearch(a, 1, 4, 5);
int x2 = Arrays.binarySearch(a, 1, 4, 4);
int x3 = Arrays.binarySearch(a, 1, 4, 2);
int x4 = Arrays.binarySearch(a, 1, 3, 10);
System.out.println("x1:" + x1 + ", x2:" + x2);
System.out.println("x3:" + x3 + ", x4:" + x4);
}
}
/*輸出結果:
x1:-4, x2:2
x3:-2, x4:-4
*/

關於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.