编程训练[C语言]——二分查找报错Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)的案例和正确代码

【输入输出样例】

样例一

Input
10
1 2 3 4 5 6 7 8 9 10
5

Output
4

说明:输入5,输出5在数组中的下标4

样例二

Input
10
2 4 7 10 19 22 23 38 56 100
20

Output
-1

Then Input
23

Output
6

输入20,没找到,返回-1;输入23,返回其下标6。

【代码实现】
(错误代码和错因分析见注释)

#include<stdio.h>

#define MAXLENGTH 100

//  这个代码是错误的,因为会出现StartIndex>EndIndex的情况,而这个函数没有考虑到这个情况
//  报错信息:Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)
//int IndexOfx(int *a,int x,int StartIndex,int EndIndex){
//    int MidIndex=(EndIndex-StartIndex)/2+StartIndex;
//    if(StartIndex==EndIndex){
//        if(x==a[StartIndex]){
//            return StartIndex;
//        }
//        else{
//            return -1;
//        }
//    }
//    else{
//        if(x<a[MidIndex]){
//            return IndexOfx(a,x,StartIndex,MidIndex-1);
//        }
//        else{
//            return IndexOfx(a,x,MidIndex,EndIndex);
//        }
//    }
//}

int IndexOfx(int *a,int x,int low,int high){
    int index=-1;
    int mid;
    while(low<=high){
        mid=(low+high)/2;
        if(x<a[mid]){
            high=mid-1;
        }
        else if(x>a[mid]){
            low=mid+1;
        }
        else if(x==a[mid]){
            index=mid;
            return index;
        }
    }
    return index;
}

int main(){
    int n;
    int a[MAXLENGTH];
    int x;
    int index;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",a+i);
    }
    while(scanf("%d",&x)==1){
        index=IndexOfx(a,x,0,n-1);
        printf("%d\n",index);
    }
    return 0;
}

发布了36 篇原创文章 · 获赞 41 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/umbrellalalalala/article/details/87937207