Untitled
raw download clone
TEXT
views 26
,
size 878 b
#include"function.h"

int BS(int *, int, int);//the meaning of *?

int b[(int)2e6]; //為什麼需要轉換型別?

int main(){
	int n, t;
	scanf("%d%d", &n, &t);
	for(int i=0; i<n; i++){
		scanf("%d", &b[i]);
	}
	for(int i=0; i<t; i++){
		int a;
		scanf("%d", &a);
		printf("%d is at index: %d\n", a, BS(b, a, n));
	}
	return 0;
}
int BS(int * b, int a, int n) // b:陣列名, a:欲尋找的數字, n:陣列長度
{
    int L = 0, R = n;
    while(L<R){
        int mid = (L+R)/2;
        if(b[mid]==a){
            return mid;
        }
        else if(b[mid]<a){
            //printf("mid:%d, a:%d, n:%d\n", mid, a, n);
            L = mid;
            return BS(b, a, n-mid);
        }
        else {
            //printf("mid:%d, a:%d, n:%d\n", mid, a, n);
            R = mid;
            return BS(b, a, mid+1);
        }
    }
}
close fullscreen
Login or Register to edit or fork this paste. It's free.