#include <stdio.h> int binary_search(int *arr,int n, int x) { int head = 0, tail = n - 1, mid; while(head <= tail) { mid = (head + tail) >> 1; if (arr[mid] == x) return mid; if (arr[mid] < x) head = mid + 1; else tail = mid - 1; } return -1; } int main() { int arr[100] = { 0 }, n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d",&arr[i]); } int x; while (~scanf("%d",&x)) { printf("%d\n",binary_search(arr,n,x)); } return 0; }
#include <stdio.h> //00000001111111 查找第一个1 int binary_search(int *arr,int n) { // 将tail=n-1改为n,对尾指针增加一个虚拟位 int head = 0, tail = n, mid; while(head < tail) { mid = (head + tail) >> 1; if (arr[mid] == 0) head = mid + 1; else tail = mid; } return head == n ? -1 : head; } int binary_search2(int *arr,int n) { // 将head=0改为head=-1增加一个虚拟位 int head = -1, tail = n - 1, mid; while (head < tail) { mid = (head + tail + 1) >> 1; if (arr[mid] == 0) { tail = mid - 1; } else { head = mid; } return head; } } int main() { int arr[100] = { 0 }, n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d",&arr[i]); } printf("%d\n",binary_search(arr,n)); return 0; }
原文:https://www.cnblogs.com/d1012181765/p/15032481.html