ACM UVA-10611

binary Search

int N[50005];
void binarySearch(int search,int n){
    int left = 0,right = n-1;
    while(left <= right){
        int mid = (left+right)/2;
        if(N[mid]<search){
            left = mid+1;
        }else if(N[mid]>search){
            right = mid-1;
        }else if(N[mid] == search){
            if(mid+1>n-1 && mid-1<0)
                printf("X X\n");
            else if(mid+1>n-1)
                printf("%d X\n",N[mid-1]);
            else if(mid-1<0)
                printf("X %d\n",N[mid+1]);
            else
                printf("%d %d\n",N[mid-1],N[mid+1]);
            return;
        }
    }
    if(left>n-1 && left-1<0){
        printf("X X\n");
    }else if(left>n-1){
        printf("%d X\n",N[left-1]);
    }else if(left-1<0){
        printf("X %d\n",N[left]);
    }else{
        printf("%d %d\n",N[left-1],N[left]);
    }

}
int main(int argc, char const* argv[])
{
    int n;
    while(~scanf("%d",&n)){
        scanf("%d",&N[0]);
        int cmp = N[0];
        int tmp;
        int count = 1;
        for(int i = 1;i<n;i++){
            scanf("%d",&tmp);
            if(tmp != cmp){
                N[count++] = tmp;
                cmp = N[count-1];
            }

        }
        int q;
        scanf("%d",&q);
        int qq;
        while(q--){
            scanf("%d",&qq);
            binarySearch(qq,count);
        }
    }

    return 0;
}