二分法计算点所在的范围

float axx[] = {10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300};
int arrLen = sizeof(axx)/sizeof(axx[0]);

void startSearch(int mid,int start,int end,int target){
    
    assert(start >= 0);
    assert(end <= arrLen);
    assert(start <= end);
    assert(mid>=start);
    assert(mid<=end);
    
    if (target >= axx[mid]) {
        
        if (target <= axx[mid+1]) {
            cout << "1找到此位置,位置为" << mid << endl;
            return;
        }else
        {
             //在后半部分
            int newMid = (end - mid)/2 + mid;
            startSearch(newMid,mid, end,target);
        }
    }else
    {
       
        if (mid >= 1) {
            if (target >= axx[mid-1]) {
                cout << "2找到此位置,位置为" << mid -1 << endl;
                return;
            }else
            {
                //在前半部分
                int newMid = (mid - start)/2 + start;
                startSearch(newMid, start, mid,target);
            }
        }else
        {
            cout << "3找到此位置,位置为" << 0 << endl;
            return;
        }
    }
}


int main(){
    
    int mid = arrLen/2;
    
    assert(arrLen > 0);
    
    int target = 0;
    for (int i = 11 ; i < 299; ++i) {
        
        target = i;
        if (target < axx[0] || target > axx[arrLen-1]) {
            cout << "超出了范围" << endl;
            exit(-1);
        }
        
        startSearch(mid,0,arrLen - 1,target);
    }
    return 0;
}



前提是需要查找的数组为 有序的


   

你可能感兴趣的:(二分法计算点所在的范围)