510 二分搜尋法

import java.util.Scanner;
public class JPA510 {
    public static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] argv) {
        search();
        search();
    }

    public static void search() {
        int[] data = {5, 9, 13, 15, 17, 19, 25, 30, 45}; // 已排序資料

        System.out.print("請輸入要找尋的資料:");

        int target = keyboard.nextInt();

        int high=data.length-1;
        int low=0;
        int mid=(high+low)/2;;
        int times=0;

        while(low<=high){

        times++;
        mid=(high+low)/2;

        System.out.println("尋找區間"+low+"("+data[low]+").."+high+"("+data[high]+"), 中間 : "+data[mid]);

        if(target==data[mid]){
        break;
        }
        else if(target<data[mid]){
        high=mid-1;
        }
        else{
        low=mid+1;
        }
        }

        System.out.println("經過"+times+"次的尋找");

        if(target==data[mid]){
       System.out.println("您要找的資料在陣列中的第"+mid+"位置");
        }
        else{
        System.out.println(target+"不在陣列中");
        }

    }
}

沒有留言:

張貼留言