日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二分查找的各种条件

發布時間:2024/9/30 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二分查找的各种条件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
int firstEqual(int *a, int beg, int end, int x) {// a[i-1] < x <= a[i]int s = beg - 1;int t = end + 1;while ( s + 1 < t){int mid = s + (t - s)/2;if (x > a[mid])s = mid;elset = mid;}//要返回后面的坐標, 所以要對后面的坐標進行判斷if (t == end + 1 || a[t] != x)return -1;return t;}// a[i - 1]<= x < a[i], 對前面的坐標進行判斷 int lastEqual(int *a, int beg, int end, int x) {int s = beg -1;int t = end +1;while (s +1 < t) {int mid = s + (t - s) /2;if (x >= a[mid])s = mid;elset = mid;}if (s == beg - 1 || a[s] != x)return -1;return s; }// a[i - 1] <= x <a[i], 判斷后面的坐標 int firstBigger(int *a, int beg, int end, int x) {//找到比x大的第一個數int s = beg - 1;int t = end + 1;while (s + 1 < t) {int mid = s + (t - s)/2;if (x >= a[mid])s = mid;elset= mid;}if (t == end + 1 || a[t] <= x)return -1;return t; }//a[i-1] < x <= a[i], 判斷前面的坐標 int lastLess(int *a, int beg, int end, int x) {//找到比x小的最后一個數int s = beg - 1;int t = end + 1;while (s +1 < t){int mid = s + (t - s)/2;if (x > a[mid])s = mid;elset = mid;}if (s == beg - 1 || a[s] >= x)return -1;return s; }int main() {int a[] = {1,2,2,2,2,2,5,5,5,5,5};//10int b[] = {1,3};int c[] = {1,2,5,6,6,6,6};//6int d[] = {3,4,6,6,7,7,9,10,10};//8cout<<firstBigger(a,0,10,2)<<" "<<firstBigger(a,0,10,5)<<" "<<firstBigger(a,0,10,3)<<" "<<firstBigger(a,0,10,1)<<endl;cout<<firstBigger(b,0,1,1)<<" "<<firstBigger(b,0,1,2)<<endl;cout<<firstBigger(c,0,6,2)<<" "<<firstBigger(c,0,6,5)<<" "<<firstBigger(c,0,6,3)<<" "<<firstBigger(c,0,6,6)<<endl;cout<<firstBigger(d,0,8,3)<<" "<<firstBigger(d,0,8,4)<<" "<<firstBigger(d,0,8,6)<<" "<<firstBigger(d,0,8,7)<<" "<<firstBigger(d,0,8,9)<<" "<<firstBigger(d,0,8,10)<<" "<<firstBigger(d,0,8,2)<<endl;cout<<endl;cout<<lastLess(a,0,10,2)<<" "<<lastLess(a,0,10,5)<<" "<<lastLess(a,0,10,3)<<" "<<lastLess(a,0,10,1)<<endl;cout<<lastLess(b,0,1,1)<<" "<<lastLess(b,0,1,2)<<endl;cout<<lastLess(c,0,6,2)<<" "<<lastLess(c,0,6,5)<<" "<<lastLess(c,0,6,3)<<" "<<lastLess(c,0,6,6)<<endl;cout<<lastLess(d,0,8,3)<<" "<<lastLess(d,0,8,4)<<" "<<lastLess(d,0,8,6)<<" "<<lastLess(d,0,8,7)<<" "<<lastLess(d,0,8,9)<<" "<<lastLess(d,0,8,10)<<" "<<lastLess(d,0,8,2)<<endl;return 0; }


所有條件的二分查找只有兩種方式

1.

?mid ? ? ? ? mid

a[i-1]<x<=a[i]

? ?s ? ? ? ? ? ? t


因為t的那一邊有一個等號,所以當 a[mid] >= x時,t = mid


?1.1 返回大于等于x的第一個 return t

? 1.2 ?返回小于x的最后一個 return s

2.?

?mid ? ? ? ? mid

a[i-1]<=x<a[i]

? ?s ? ? ? ? ? ? t


因為s的那一邊有等號,所以當a[mid] <=x時,s = mid

2.1 返回小于等于x的最后一個 return s

2.2 返回大于x的第一個 return t


總結

以上是生活随笔為你收集整理的二分查找的各种条件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。