二分查詢細節永不忘

2021-10-13 07:54:10 字數 1176 閱讀 2601

二分查詢中大於小於,甚至判斷條件中的 < <= 很容易弄混。下面一起來捋清楚,保證了解原理,不會再錯。重點的概念在於選區的區間!

我建議選取的區間為左閉右閉,即[l,r]。當然其他方式也可以,我們不做講述。

因此需要注意以下三點即可:

1.r = arr.length()-1而不是length(),這樣使得r為末數的下標,有意義。

2. 判斷終止條件為l < = r,因為 l,r 都是尋找目標,當其相等時,代表還有乙個待驗證目標。

3. 每次縮小範圍時,l = mid-1, r = mid + 1。原因很簡單,我們已經判斷過mid 並不是我們的target,因此下次判斷的區間並不需要包含mid!

package com.mysearch;

public

class

binsearch

else

if(target < arr[mid]

)else

if(target > arr[mid]

)else

}else

}// 遞迴方法入口,呼叫方

public

static

intsearch

(int

arr,

int target)

// 非遞迴方法

public

static

intsearchwithwhile

(int

arr,

int target)

else

if(target < arr[mid]

)else

if(target > arr[mid]

)else

}return-1

;}public

static

void

main

(string[

] args)

, target));

system.out.

println

(searchwithwhile

(new

int[

], target));

}}

二分查詢細節問題

1.1 兩種實現 情況一 right nums.length int binary search int nums,int target else if nums mid target else if nums mid target 因為迴圈的結束條件是 left right,它們指向的元素未被判斷...

二分的細節

最普通的二分 搜尋區間 left right 每次搜尋mid後一分為二 left mid 1 和 mid 1 right 出while迴圈條件 left right 1 int binarysearch int nums,int target return 1 搜尋左側邊界的二分int left b...

迭代二分查詢二分查詢

在寫這篇文章之前,已經寫過了幾篇關於改迭代二分查詢主題的文章,想要了解的朋友可以去翻一下之前的文章 bentley在他的著作 writing correct programs 中寫道,90 的計算機專家不能在2小時內寫出完整確正的二分搜尋演算法。難怪有人說,二分查詢道理單簡,甚至小學生都能明確。不過...