Open darwinrlo opened 4 years ago
In Python, // is the operator for "floor division." 3 // 2 = 1. Note that -3 // 2 = -2 -- -2 is smaller than -1.
A good implementation would set start to the index of the first element of the segment and end to the index of the last element. When the segment is simply the entire array, start is 0 and end is arr.length - 1. If the middle element is not equal to the target element and start equals end, then return -1.
If the order of the sort is not known, then compare the first element with the last element. For example, if the first element is less than the final element, then it is sorted in ascending order. The sort order determines which segment to recurse on if the middle element is not a match.
end - start gives the number of elements between the start of the last element and the start of the first element. Note that the last element is not included in this count.
If start and end are both odd or both even, then their difference is even. If one is odd while the other is even, their difference is even.
If there are even number of elements, then the midpoint is between the two middle elements. The floor or ceiling of (start + end)/2 will need to be taken to choose one of the two middle keys. If there are an odd number of elements, then there is a single element in the middle and neither the floor nor ceiling will need to be taken.
In Java, it is tempting to use (start + end)/2. But if start and end are very large, the numerator could overflow. It is better to use start + (end - start)/2. (The floor is implicitly taken here.) This makes the numerators involved smaller and less likely to overflow. In Python, there is no integer overflow so (start + end)/2 works just fine.
If the input binary tree is not stipulated to be balanced, then in the worst case, it could be a linked list, meaning the tree would have height n. This confers DFS a worst-case running time of O(n) and space complexity of O(n).
Heaps
Min-Heaps
Max-Heaps
Patterns
Solutions