您好,登錄后才能下訂單哦!
普通二分法查找元素:
#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; }
顯示結果:
那如果是查找數組中第一次出現的那個元素,這種方法顯然是不可行。
就需要修改一小下下
#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; }
顯示結果:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。