Binary search for lowest index of an element
binary search minimum index
binary search python
recursive binary search
binary search applications
minimum difference element
binary search program in c++
I want to implement a binary search function which returns the lowest index of the element to be searched. Here is my code:
def binarySearch(arr,x): n=len(arr) if n==1: if arr==x: return 0 else: return -1 # not in list else: m=int(n/2) if x <= arr[m]: return binarySearch(arr[:m],x) else: return m+binarySearch(arr[m+1:],x)
However, this doesn't work correctly. Can someone help me?
def binarySearch(arr,x): if len(arr) == 0: return 0 else: m=int(len(arr)/2) if arr[m] == x: c = 1 while arr[m-c] == x: c += 1 return m-c+1 else: if x < arr[m]: return binarySearch(arr[:m],x) else: return binarySearch(arr[m+1:],x)
This fixes your issues while also giving you the lowest index
Binary Search, This program uses a modified version of the binary search algorithm that returns the element with the smallest index that matches the search element. In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
You can find the index of an element which is equal to
x by just adding a test for equality into the
else part of your function:
def binarySearch(arr,x): n=len(arr) if n==1: if arr==x: return 0 else: return -1 # not in list else: m = int(n/2) if x < arr[m]: return binarySearch(arr[:m],x) elif x == arr[m]: return m else: return m + binarySearch(arr[m+1:],x)
This prevents the problem of recursing past the solution, mentioned by @Fruitpunchsalami
However, this won't get you the lowest index:
>>> binarySearch([1,2,3,3,4,4], 3) 3
Here the right answer would be 2.
A further problem is the handling of elements which are not found, due to the special case of
-1. We get:
>>> binarySearch([1,2,3,3,6,6], 4) 2
I would be tempted to suggest a generic solution whereby you find the index of the largest element less than
x, and then check the element in the position one up from that one.
Finding the largest element less than
x can be done in logarithmic time; checking the element to the right is constant time, so you still get O(log n):
def binarySearch(arr,x): '''Returns the lowest index of the element equal to `x` or NaN if not found.''' def innerBinarySearch(arr, x): '''Find index of largest element strictly less than `x`.''' if len(arr) == 0: return -1 m = len(arr) // 2 if x <= arr[m]: return innerBinarySearch(arr[:m], x) else: return m + 1 + innerBinarySearch(arr[m + 1:], x) idx = innerBinarySearch(arr,x) + 1 if 0 <= idx < len(arr) and arr[idx] == x: return idx return float('nan')
Do it all in one function:
def binarySearch(arr,x): '''Returns the lowest index of the element equal to `x` or NaN if not found.''' if len(arr) == 0: return float('nan') m = len(arr) // 2 if arr[m] < x: return m + 1 + binarySearch(arr[m + 1:], x) elif x < arr[m] or (0 < m and arr[m-1] == x): return binarySearch(arr[:m], x) else: return m
Find position of an element in a sorted array of infinite numbers , So in order to find position of key, first we find bounds and then apply binary search algorithm. Let low be pointing to 1st element and high pointing to 2nd element Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist.
def index_equals_value_search(arr): left, right = 0, len(arr)-1 lowest = -float('inf') while left<=right: mid = (left+right)//2 print(mid, left, right, arr[mid]) if arr[mid] == mid: lowest = min(lowest, mid) right = mid-1 elif arr[mid]<0: left = mid+1 elif arr[mid]<mid: left = mid+1 elif arr[mid]>mid: right = mid-1 if lowest == -float('inf'): return -1 return lowest arr = [-6,-5,-4,-1,1,3,5,7] index_equals_value_search(arr)
Binary search algorithm, find the index of a given key · matoski.com, Binary search is used to find the index of an element in a sorted array, and if At every step, consider the array between low and high indices Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array. The Naive Approach is to run a for loop and check given elements in array. Run a for loop and for i = 0 to n-1 2. Take first = -1 and last = -1 3. When we find element first time then we update
Binary search algorithm, However, binary search can be used to solve a wider range of problems, such as finding the next-smallest or next-largest element in the array relative to the Arrays.binarySearch () is the simplest and most efficient method to find an element in a sorted array in Java. where data_type can be any of the primitive data types: byte, char, double, int, float, short, long and Object as well. Searches the specified array of the given data type for the specified value using the binary search algorithm.
Binary search, This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is Element found at index 1 Performance of Binary Search Algorithm: We know that at each step of the algorithm, our search space reduces to half. That means if initially our search space contains n elements, then after one iteration it contains n/2, then n/4 and so on.. n -> n/2 -> n/4 -> … -> 1. Suppose after k steps our search space is
- Possible duplicate of Binary search (bisection) in Python
- yeah , cool . But I don't want to use bisect_left . Any suggestions ?
- I don't understand. Can u show me which part of the code ?
- n=len(arr) is not needed, just add the logic to the if statement below
- u mean to change the if statement from if n == 1 to len(arr) == 1 ?
- Special casing
arr[m-1]won't work in the general case.
- Does that fix it? I have to get back to work and that's the quickest hack I can think of.
- Nice, that looks better to me. Runtime is no longer logarithmic, tho I'm not sure if that can be guaranteed given OP's question.
- yeah , its a good solution , but as wildwilhelm mentioned ,it isn't in log(n) :/
- This seems to be a good solution to your problem. The array is edited to sections that are likely to contain the value. With the array [1,3,3,3,3,3,3,4,4], my solution takes 0.0001163482666015625 while his takes 6.198883056640625e-06.
- Thank for the suggestion , but my function must find the lowest index. Do you know , how to change the code to find it ?
- what does if not arr mean ?
- Here it means that arr is empty.
- so your last piece of code should be the right implementation ?
- When I try to run it , it gives me this error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() for the if not arr