import java.util.Scanner;
public class BinarySearchExample {
public static void main(String[] args) {
int[] array = {8, 11, 23, 35, 48, 51, 66, 77, 88, 99};
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入要搜尋的數值:");
int target = scanner.nextInt();
Result result = binarySearch(array, target);
if (result.found) {
System.out.println("找到數值 " + target + " 於陣列中的位置:" + result.position);
System.out.println("搜尋次數:" + result.searchCount);
} else {
System.out.println("查無該筆紀錄!");
}
scanner.close();
}
public static Result binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
int searchCount = 0;
while (left <= right) {
searchCount++;
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return new Result(true, mid, searchCount);
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return new Result(false, -1, searchCount);
}
}
class Result {
boolean found;
int position;
int searchCount;
public Result(boolean found, int position, int searchCount) {
this.found = found;
this.position = position;
this.searchCount = searchCount;
}
}
程式說明:
主要方法 (main method):
定義一個已排序的整數陣列 array。
使用 Scanner 讀取使用者輸入的目標數值。
調用 binarySearch 方法搜尋目標數值。
根據搜尋結果輸出相應的訊息。
二分搜尋方法 (binarySearch method):
初始化左右指標 (left 和 right)。
初始化搜尋次數 (searchCount)。
進行迴圈搜尋:
每次計算中間指標 (mid)。
比較中間值與目標值:
如果相等,返回結果(包含找到的位置和搜尋次數)。
如果目標值較大,調整左指標。
如果目標值較小,調整右指標。
如果迴圈結束後仍未找到,返回未找到的結果。
結果類 (Result class):
包含三個欄位:是否找到 (found)、位置 (position) 和搜尋次數 (searchCount)。
構造函數用於初始化這些欄位。
這個程式能夠有效地使用二分搜尋法,在已排序的陣列中搜尋指定數值,並根據搜尋結果輸出相應的訊息。