java binarysearch方法怎么使用

小億
111
2023-09-26 16:50:42
欄目: 編程語言

Java的BinarySearch方法可以用于在已排序的數(shù)組中快速查找指定元素的索引。它的用法如下:

  1. 確保數(shù)組已經(jīng)排序。BinarySearch方法只能用于已排序的數(shù)組。

  2. 導(dǎo)入java.util.Arrays類。BinarySearch方法在這個(gè)類中定義。

  3. 調(diào)用Arrays類的binarySearch方法,傳入已排序的數(shù)組和要查找的元素作為參數(shù)。方法的返回值是一個(gè)整數(shù),表示要查找的元素在數(shù)組中的索引。如果元素不存在,則返回一個(gè)負(fù)數(shù)。

示例代碼如下:

import java.util.Arrays;
public class BinarySearchExample {
public static void main(String[] args) {
int[] array = {1, 3, 5, 7, 9, 11, 13};
int index = Arrays.binarySearch(array, 7);
System.out.println("Element 7 is found at index " + index);
index = Arrays.binarySearch(array, 6);
System.out.println("Element 6 is found at index " + index);
}
}

上述代碼中,我們創(chuàng)建了一個(gè)已排序的數(shù)組array,并使用BinarySearch方法在數(shù)組中查找元素7和6的索引。輸出結(jié)果如下:

Element 7 is found at index 3
Element 6 is found at index -4

這說明元素7在數(shù)組中的索引是3,而元素6不存在于數(shù)組中,所以返回了一個(gè)負(fù)數(shù)。

0