cygnus
3/19/2020 - 1:13 PM

Algorithms

from typing import List

def binarySearch(nums:List[int], left:int, right:int, val:int) -> int:
	if left <= right:
		mid = (left + right) // 2
		if nums[mid] == val:
			return mid
		elif nums[mid] > val:
			return binarySearch(nums, left, mid-1, val)
		else:
			return binarySearch(nums, mid+1, right, val)
	return -1

nums = [1,2,3,4,5,6,7,8,9,10]
print(f"LIST: {nums}")
print(f"SEARCHING 10: {binarySearch(nums, 0, len(nums)-1, 10)}")
print(f"SEARCHING 11: {binarySearch(nums, 0, len(nums)-1, 11)}")
from typing import List

def binarySearch(nums: List[int], left: int, right: int, target: int) -> int:
        mid = (left + right) // 2
        
        if left < right:
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                return binarySearch(nums, mid+1, right, target)
            else:
                return binarySearch(nums, left, mid, target)
        return mid

nums = [1,2,3,4,6,7,8,9]

#RETURNS THE INDEX IF FOUND
print(f"4 FOUND AT : {binarySearch(nums, 0, len(nums), 4)}")

#RETURNS THE INDEX OF WHERE THAT NUMBER CAN BE INSERTED IN THE ARRAY IF NOT FOUND.
print(f"5 CAN BE INSERTED AT : {binarySearch(nums, 0, len(nums), 5)}")