程式設計之美 二分查詢

2021-07-13 15:47:02 字數 1128 閱讀 9304

前三個問題不講,已經解決過了

可以參見

現在寫最後兩個

1.最大的i使得arr[i]小於v,其實就是求等於v的下界的前乙個元素。

2.最小的i使得arr[i]大於v,其實就是求等於v的上界的後乙個元素。

#include 

#include

using

namespace

std;

int indexofmaxless(vector

& nums, int target)

if (left > 0)

return -1;

}int indexofminbigger(vector

& nums, int target)

if (right < len - 1)

return -1;

}int main()

; cout

<< indexofmaxless(nums, 2) << endl;

cout

<< indexofminbigger(nums, 2) << endl;

cout

<< "-------------------"

<< endl;

cout

<< indexofmaxless(nums, 0) << endl;

cout

<< indexofminbigger(nums, 0) << endl;

cout

<< "-------------------"

<< endl;

cout

<< indexofmaxless(nums, 3) << endl;

cout

<< indexofminbigger(nums, 3) << endl;

return

0;}

結果:

1

4--------------------12

-------------------

3-1

程式設計之美 二分查詢演算法

二分查詢又稱折半查詢,優點是比較次數少,查詢速度快,平均效能好 其缺點是要求待查表為有序表,且插入刪除困難。因此,折半查詢方法適用於不經常變動而查詢頻繁的有序列表。首先,假設表中元素是按公升序排列,將表中間位置記錄的關鍵字與查詢關鍵字比較,如果兩者相等,則查詢成功 否則利用中間位置記錄將表分成前 後...

《程式設計之美》 二分查詢的實現

找出乙個有序的字串陣列arr中值等於字串v的元素的序號,並返回其序號,否則返回 1 private static intbinarysearch string arr,string str return 1 public static void main string args system.out...

基礎程式設計 二分查詢

題目要求 本題要求實現二分查詢演算法。函式介面定義 position binarysearch list l,elementtype x 其中list結構定義如下 typedef int position typedef struct lnode list struct lnode l是使用者傳入的...