Binary Search Flashcards
1
Q
How it works?
A
- Check the value in the center of the array.
- If the target value is lower, search the left half of the array. If the target value is higher, search the right half.
- Continue step 1 and 2 for the new reduced part of the array until the target value is found or until the search area is empty.
- If the value is found, return the target value index. If the target value is not found, return -1.
(the data must be sorted to use binary search)
2
Q
Code ?
A
def binarySearch(arr, targetVal): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == targetVal: return mid if arr[mid] < targetVal: left = mid + 1 else: right = mid - 1 return -1 myArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] myTarget = 15 result = binarySearch(myArray, myTarget) if result != -1: print("Value",myTarget,"found at index", result) else: print("Target not found in array.")
3
Q
Big O ?
A
O(log n)