- import java.util.Scanner;
- public class JPA05 {
- 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 = 0;
- int count = 0;
- while(low<=high)
- {
- count++;
- mid = (high+low)/2;
- System.out.printf("尋找區間:%d(%d)..%d(%d),中間:%d(%d)\n",low,data[low],high,data[high],mid,data[mid]);
- if(low<mid)
- {
- low=mid+1;
- }
- else if(high>mid)
- {
- high=mid-1;
- }
- else
- {
- break;
- }
- }
- System.out.printf("經過%d次的尋找\n",count);
- if(target==data[mid])
- {
- System.out.printf("您要找的資料在陣列中第%d個位置",mid);
- }
- else
- {
- System.out.printf("%d不在陣列中\n",target);
- }
- }
- }
複製代碼 |