首页 > 编程语言 > 详细

c语言学习4

时间:2021-07-19 22:50:09      阅读:29      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

#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;
}

 

c语言学习4

原文:https://www.cnblogs.com/d1012181765/p/15032481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!