Binary Search Using C++ [Accepted]


  • 0
    G
        int searchInsert(vector<int>& v, int target) {
            int left = 0;
    	int right = v.size() - 1;
    	int mid = (left + right) / 2;
    
    	// Because array is sorted so lets knock out worst scenario when
    	// target is higher than last element so no need to search further
    	if (target > v[v.size() - 1])
    		return right+1;
    
    	while (left < right)
    	{
    		if (v[mid] == target)
    		    return mid;
    		else if (v[mid] < target)
    			left = mid + 1;
    		else
    			right =  mid;
            
    		mid = (left + right) / 2;
    	}
    	return left;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.