int bsearch(int[] arr, int key) {
int lo = 0, mid, hi = arr.length-1;
while ( lo <= hi ) { mid = (lo + hi) / 2;
if ( key < arr[mid] ) hi = mid – 1;
else if ( arr[mid] < key )
lo = mid + 1;
else return mid;
}
return -1; }
Count the number of operations (comparisons and assignments), find an original function with an input n, and give an analysis of the running time in terms of asymptotic complexity (Big-O). Please explain answer.
int bsearch(int[] arr, int key) { -> 1 time int lo = 0, mid, hi = arr.length-1; -> 1 time while ( lo <= hi ) { mid = (lo + hi) / 2; -> log(n)+1 time if ( key < arr[mid] ) hi = mid – 1; -> log(n) time else if ( arr[mid] < key ) lo = mid + 1; -> log(n) time else return mid; -> log(n) time } -> log(n)+1 time return -1; -> 1 time } Recursive formula for the given function is T(n) = T(n/2) + 1 = T(n/4) + 1 + 1 = T(n/8) + 1 + 1 + 1 ...... ...... ...... = T(n/n) + 1 + .... + 1 + 1 + 1 [log(n) +1 terms] = 1 + 1 + .... + 1 + 1 + 1 [log(n) +1 terms] = log(n) = O(logn) So, time complexity = O(logn)
Get Answers For Free
Most questions answered within 1 hours.