普通二分法查找元素:
創(chuàng)新互聯(lián)專(zhuān)注于企業(yè)成都全網(wǎng)營(yíng)銷(xiāo)推廣、網(wǎng)站重做改版、迎江網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、HTML5、商城系統(tǒng)網(wǎng)站開(kāi)發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性?xún)r(jià)比高,為迎江等各大城市提供網(wǎng)站開(kāi)發(fā)制作服務(wù)。
#include <stdio.h> #include <stdlib.h> int BinarySearch(int* a, int n, int pos) { int left = 0; int right = n-1; while (left <= right) { int mid = left+(right-left)/2; if(pos == a[mid]) { return mid; } else if(pos < a[mid]) { right = mid - 1; } else { left = mid + 1; } } return -1; } int main() { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; int ret = BinarySearch(arr, 10, 5); printf("pos : %d\n", ret); system("pause"); return 0; }
顯示結(jié)果:
那如果是查找數(shù)組中第一次出現(xiàn)的那個(gè)元素,這種方法顯然是不可行。
就需要修改一小下下
#include <stdio.h> #include <stdlib.h> int BinarySearch(int* a, int n, int pos) { int left = 0; int right = n-1; while (left <= right) { int mid = left+(right-left)/2; if(pos == a[mid]) { while(mid-1 >= 0 && pos == a[mid-1]) { mid = mid-1; } return mid; } else if(pos < a[mid]) { right = mid - 1; } else { left = mid + 1; } } return -1; } int main() { int arr1[10] = {1,2,3,4,5,6,7,8,9,10}; int arr2[13] = {1,2,3,4,5,5,5,5,6,7,8,9,10}; int ret1 = BinarySearch(arr1, 10, 5); int ret2 = BinarySearch(arr2, 10, 5); printf("pos1 : %d\n", ret1); printf("pos1 : %d\n", ret2); system("pause"); return 0; }
顯示結(jié)果:
網(wǎng)站題目:二分法查找元素位置
轉(zhuǎn)載源于:http://jinyejixie.com/article6/ppepig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站導(dǎo)航、關(guān)鍵詞優(yōu)化、ChatGPT、面包屑導(dǎo)航、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)