返回列表 發帖
  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.         int high = data.length-1 ;
  15.         int low  = 0;
  16.         int mid = 0;
  17.         int n = 0;
  18.         
  19.         while(low<=high)
  20.         {
  21.                 System.out.printf("尋找區間:%d(%d)..%d(%d),中間:%d(%d)",low,data[low],high,data[high],mid,data[mid]);

  22.                 n++;
  23.         mid=(high+low)/2;
  24.         
  25.             if(target>data[mid]){
  26.                    
  27.                     low = mid+1;
  28.                    
  29.             }
  30.             else if(target<data[mid]){
  31.                    
  32.                     high = mid-1;
  33.                    
  34.             }
  35.             else{
  36.                    
  37.                     break;
  38.                    
  39.             }
  40.                
  41.                            
  42.         }
  43.         
  44.         System.out.println("經過"+n+"次的搜尋");
  45.         if(target == data[mid]){
  46.                
  47.                 System.out.println("您要找的資料在陣列中的第"+mid+"個位置");
  48.         }
  49.         else{
  50.                
  51.                 System.out.println(target+"不在陣列中");
  52.                
  53.         }
  54.     }
  55. }
複製代碼

TOP

返回列表