In: Computer Science
Given an array storing integers ordered by value, modify the binary search routine to return the position of the integer with the greatest value less than K when K itself does not appear in the array. Return ERROR if the least value in the array is greater than K.
int findPosition(int data[], int size, int k) { if(size == 0 || data[0] > k) { return ERROR; } int left = 0; int right = size - 1; while(left < right) { int mid = (left + right)/2; // If data is more, Then right limit should be reduced. if(data[mid] > k) { right = mid - 1; // Else, We can reduce our left limit. } else if(data[mid] < k) { left = mid; } } return left; // Return the left position. }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.