Java 二分查詢程式(遞迴)


以下是 Java 中遞迴二分查詢的程式 -

範例

 線上演示

public class Demo{
   int rec_bin_search(int my_arr[], int left, int right, int x){
      if (right >= left){
         int mid = left + (right - left) / 2;
         if (my_arr[mid] == x)
         return mid;
         if (my_arr[mid] > x)
         return rec_bin_search(my_arr, left, mid - 1, x);
         return rec_bin_search(my_arr, mid + 1, right, x);
      }
      return -1;
   }
   public static void main(String args[]){
      Demo my_object = new Demo();
      int my_arr[] = { 56, 78, 90, 32, 45, 99, 104};
      int len = my_arr.length;
      int x = 104;
      int result = my_object.rec_bin_search(my_arr, 0, len - 1, x);
      if (result == -1)
         System.out.println("The element is not present in the array");
      else
         System.out.println("The element has been found at index " + result);
   }
}

輸出

The element has been found at index 6

名為 Demo 的一個類包含二分查詢函式,它採用需要查詢的左右和值。一旦實現二分查詢後,一個 main 函式建立 Demo 物件的一個例項,並將值分配給一個數組。透過傳遞一個特定值進行引數搜尋,可以在陣列中呼叫此二分查詢函式。如果找到,將顯示該索引,否則,顯示一條相關訊息。

更新於:2020 年 7 月 4 日

6 千次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告推薦
© . All rights reserved.