阿摩線上測驗 登入

申論題資訊

試卷:108年 - 108 中華郵政股份有限公司_職階人員甄試_營運職/系統分析_專業科目(1):資訊系統規劃開發(含系統分析、程式設計、開發程序、資料庫系統、網際網路服務及應用)#75231
科目:資訊系統開發與維護概要
年份:108年
排序:0

申論題內容

第三題: 請以 JAVA 語言設計一程式,該程式在使用者輸入特定數值後,以二分搜尋法(binary search),搜尋陣列內是否存在該數值;如果存在,則輸出該數值於陣列中的順位以及搜尋幾 次才找到;如果該數值不存在,則輸出"查無該筆紀錄!"之訊息。所設計的程式一定要使用陣 列結構和迴圈指令。【25 分】             陣列中的數值為:8,11,23,35,48,51,66,77,88,99

詳解 (共 1 筆)

詳解 提供者:hchungw
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)。
構造函數用於初始化這些欄位。
這個程式能夠有效地使用二分搜尋法,在已排序的陣列中搜尋指定數值,並根據搜尋結果輸出相應的訊息。