ProAnswers.org

algorithm Search for a key in a sorted array(Binary Search)

algorithm Search for a key in a sorted array(Binary Search)

int bin_search(int a[], int size, int x){

	    int lower = 0, upper = size-1, mid;

	    while(lower <= upper){

	        mid = (lower + upper)/2;

	        if(x < a[mid])

	            upper = mid - 1;

	        else if(x > a[mid])

	            lower = mid + 1;

	        else

	            return mid;

	    }

	    return -1;

	}