Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

C++, binary search recursive

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int ret = 0;
		
        if (nums.size() == 0)
            return -1;
  
        if (nums[nums.size()/2] < target) {
            vector<int> halfVec(nums.begin()+nums.size()/2+1,nums.end());
            auto retIdx = search(halfVec,target);
            if (retIdx == -1) return -1;
            ret += retIdx +  nums.size()/2+1;
        } else if (nums[nums.size()/2] > target) {
            vector<int> halfVec(nums.begin(),nums.begin()+nums.size()/2);
            ret = search(halfVec,target);
        } else {
            ret = nums.size()/2;
        }
         
        return ret;
        
    }
};
Source by leetcode.com #
 
PREVIOUS NEXT
Tagged: #binary #search #recursive
ADD COMMENT
Topic
Name
2+6 =