开发者

Programming Pearls Problem: Checking for sorted array in binary search

In Programming Pearls (second edition) Column 5, problem 5 the question is about implementing binary search on an unsorted array.

How can you add par开发者_JAVA技巧tial checking to the function at significantly less than O(n-1) cost?

I know you can check with every iteration and achieve O(log n), but the hint in the back suggests there is an O(1) solution.

What is that solution?


Summary

Partially checking if the array is sorted so that the binary search is applicable can be done in O(log n), as the OP said, and in O(1). The O(log n) method is to check each of the probes against the previous probe to make sure that it compares properly (less than, greater than). The O(1) method is to just check the final element found by binary search and one next to it so that if the sought-after element wasn't found, at least the correct place for insertion was found. If the sought-after element was found, then that is a good O(1) partial check.

Longer explanation

The part of the problem before the code block says that a common problem is using binary search on an unsorted array. Basically, how can use partial checking to check if an array is sorted in less than O(n-1) cost?

The O(log n) solution is to check each of the binary search probes meshes with respect to the previous probe (is less than or greater than it is expected to be). This doesn't guarantee that the array is sorted, but it is a good partial check.

The only O(1) check that I can think of is to check the final place that is searched such that its value and the neighboring values mesh with the idea of where the searched for element should be, even if the element wasn't found. It's a pretty good partial check: if the element is found then things are probably working correctly. If it wasn't, then check the elements around where it should be that such that there is one less than the searched for element and then one that is greater than the searched for element. However, I do realize that checking in this manner means that the binary search, which is O(log n), has already been done so I don't know if this is truly O(1). However, it only adds O(1) to the overall search so I think that it is applicable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜