共計 683 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
Java 的 BinarySearch 方法可以用于在已排序的數(shù)組中快速查找指定元素的索引。它的用法如下:
- 確保數(shù)組已經(jīng)排序。BinarySearch 方法只能用于已排序的數(shù)組。
- 導(dǎo)入 java.util.Arrays 類。BinarySearch 方法在這個類中定義。
- 調(diào)用 Arrays 類的 binarySearch 方法,傳入已排序的數(shù)組和要查找的元素作為參數(shù)。方法的返回值是一個整數(shù),表示要查找的元素在數(shù)組中的索引。如果元素不存在,則返回一個負(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)建了一個已排序的數(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ù)組中,所以返回了一個負(fù)數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完