In the binary search algorithm, we set the mid as:
mid = (start + end)/2 which is same as
mid = start/2 + end/2 and also equal to
mid = start + (end - start)/2
but all of the three give different results being the same arithmetic expression. How do these vary during the computation process?
This was the code to find the last occurrence of an element in a vector array using binary search:
int lastOccurrence(vector<int> arr, int size, int key){
int start = 0, end = size - 1;
int last = -1;
// int mid = start/2 + end/2;
int mid;
while(start <= end){
// mid = start + (end - start)/2;
mid = (start + end)/2;
if(key == arr[mid]){
last = mid;
start = mid + 1;
}
else if(key > arr[mid]){
start = mid + 1;
}
else{
end = mid - 1;
}
cout << "start: " << start << "\tend: " << end << "\tmid: " << mid << endl;
}
return last;
}
The values being passed to the function are:
int main(){
vector<int> arr = {1,2,3,4,4,4,4,5,6,7,11};
int size = arr.size();
int key = 4;
cout << "First occurrence of " << key << " is at index " << firstOccurrence(arr, size, key) << endl;
cout << "Last occurrence of " << key << " is at index " << lastOccurrence(arr, size, key) << endl;
return 0;
}
If the mid element equals the required "key" element then the mid index is stored in a variable and start is updated to mid + 1 so that it can search the right part of the array for any other occurrence of the "key". If the "key" is found to be less than the mid element it implies that the element is not present beyond the mid element and the end is updated to mid - 1 to search in the left part of the array, and similarly to search the right part if "key" is found to be greater than the mid element.
It gave different results when mid = start/2 + end/2 was used and mid = (start + end)/2 was used. How is this affected during the computation process?
(1+3)/2
is not the same as1/2+3/2
. – Tapdancemid = start + (end - start)/2
is the same as2*mid = 2*start + (end - start)
is the same as2*mid = 2*start + end - start
is the same as2*mid = start + end
is the same asmid = (start + end)/2
. Please show your values. (this all assumingstart+end
doesn't overflow) – Contretempsint
, so the result is anint
. Sostart/2
rounds towards zero (e.g.3/2
gives1
, not1.5
), as doesend/2
. As an example,1/2 + 3/2
computes1/2
and3/2
separately, producing0
and1
respectively, and their sum is1
. Whereas(1+3)/2
computes1+3
first, giving4
, and divides that by2
, producing2
. – Astri