Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upUpdate ternary_search.py #3055
Update ternary_search.py #3055
Conversation
|
The changes don't make the functions ternary search anymore. |
| oneThird = (left + right) / 3 + 1 | ||
| twoThird = 2 * (left + right) / 3 + 1 | ||
| oneThird = (left + right) / 2 - 1 | ||
| twoThird = (left + right) / 2 + 1 |
peteryao7
Oct 8, 2020
•
Ternary search is a divide and conquer algorithm like binary search that's supposed to split the search space into three equal portions. Here, you're splitting it into two halves and the middle element as the second third.
Using floating point division / over integer division // is causing an entirely different bug, but the index calculations themselves are fine.
Another way to calculate oneThird and twoThird that prevents overflow problems in other languages is by doing it this way:
oneThird = left + (right - left) // 3
twoThird = right - (right - left) // 3
zyrch
Oct 8, 2020
Author
By dividing the search space into three in ternary search we are able to find the minimum or maximum of convex functions, (if it is not convex then binary search is directly applicable). Now comparing three values in the search space allows us to eliminate one portion at a time. Now to increase the efficiency of the program we can decrease the distance two intervals and still get the same result, this method is also known as dichotomous search.
peteryao7
Oct 8, 2020
•
Binary and ternary search are examples of dichotomous search. What ternary search lets you do over binary search is omit two sections, or 2/3, of the search space on each iteration (as opposed to 1/2 in binary search), which is correctly done at the end of the loop:
elif target < A[oneThird]:
right = oneThird - 1
elif A[twoThird] < target:
left = twoThird + 1
else:
left = oneThird + 1
right = twoThird - 1
The goal of the function is simply to find a specified value, so binary search will suffice, but by changing how the boundaries are calculated and changing the time complexity to O(log2(n)), you implemented binary search, not ternary search.
Also, even though they're very similar, O(log2(n)) is less efficient than O(log3(n)).
zyrch
Oct 8, 2020
Author
You are correct I just realized we are searching in a sorted array, and my method is a better only in the case when ternary search is used to min or max of convex functions or data sets.
| oneThird = (left + right) / 3 + 1 | ||
| twoThird = 2 * (left + right) / 3 + 1 | ||
| oneThird = (left + right) / 2 - 1 | ||
| twoThird = (left + right) / 2 + 1 |
Describe your change:
Reduces the overall complexity of the algorithm for discrete searches (like in a list)
Checklist:
Fixes: #{$ISSUE_NO}.