返回列表 發帖
  1. import java.util.Scanner;
  2. public class JPA05 {
  3.     public static Scanner keyboard = new Scanner(System.in);
  4.    
  5.     public static void main(String[] argv) {
  6.         search();
  7.         search();
  8.     }
  9.    
  10.     public static void search() {
  11.         int[] data = {5, 9, 13, 15, 17, 19, 25, 30, 45}; // 已排序資料

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

  13.         int target = keyboard.nextInt();
  14.    
  15.         int high = data.length-1;
  16.         int low = 0;
  17.         int mid = 0;
  18.         int count = 0;
  19.         while(low<=high)
  20.         {
  21.                 count++;
  22.                 mid = (high+low)/2;
  23.                 System.out.printf("尋找區間:%d(%d)..%d(%d),中間:%d(%d)\n",low,data[low],high,data[high],mid,data[mid]);
  24.                 if(low<mid)
  25.                 {
  26.                         low=mid+1;
  27.                 }
  28.                 else if(high>mid)
  29.                 {
  30.                         high=mid-1;
  31.                 }
  32.                 else
  33.                 {
  34.                         break;
  35.                 }
  36.         }
  37.         System.out.printf("經過%d次的尋找\n",count);
  38.         if(target==data[mid])
  39.         {
  40.                 System.out.printf("您要找的資料在陣列中第%d個位置",mid);
  41.         }
  42.         else
  43.         {
  44.                 System.out.printf("%d不在陣列中\n",target);
  45.         }
  46.     }
  47. }
複製代碼

TOP

返回列表