"""Binary Search
Recursive
- 2 Separate functions
--> Perhaps more readable?
- Or just one function that recursively calls itself
--> Perhaps more logical?
"""
## With 2 separate functions
def bin_recur(lst, item):
return go_bin_recur(lst, item, 0, len(lst) - 1)
def go_bin_recur(lst, item, low, high):
if low <= high:
mid = (low + high) // 2
if item > lst[mid]: # To the left
low = mid + 1
elif item < lst[mid]: # To the right
high = mid - 1
else: # Found
return mid
return go_bin_recur(lst, item, low, high)
return [] # Not found
## With one function
def bin_recur(lst, item, low=0, high=None):
if high is None:
high = len(lst) - 1
if low <= high:
mid = (low + high) // 2
if item > lst[mid]: # To the left
low = mid + 1
elif item < lst[mid]: # To the right
high = mid - 1
else: # Found
return mid
return bin_recur(lst, item, low, high)
return [] # Not found
"""Whats your preference?"""
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;
}
};
"""Binary Search
Recursive
- 2 Separate functions
--> Perhaps more readable?
- Or just one function that recursively calls itself
--> Perhaps more logical?
"""
## With 2 separate functions
def bin_recur(lst, item):
return go_bin_recur(lst, item, 0, len(lst) - 1)
def go_bin_recur(lst, item, low, high):
if low <= high:
mid = (low + high) // 2
if item > lst[mid]: # To the left
low = mid + 1
elif item < lst[mid]: # To the right
high = mid - 1
else: # Found
return mid
return go_bin_recur(lst, item, low, high)
return [] # Not found
## With one function
def bin_recur(lst, item, low=0, high=None):
if high is None:
high = len(lst) - 1
if low <= high:
mid = (low + high) // 2
if item > lst[mid]: # To the left
low = mid + 1
elif item < lst[mid]: # To the right
high = mid - 1
else: # Found
return mid
return bin_recur(lst, item, low, high)
return [] # Not found
"""Whats your preference?"""
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;
}
};