tags:

views:

68

answers:

1

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

How can you add partial 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?

+2  A: 

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.

Justin Peel
Well written. I was wondering if this might be the solution, but it seemed a little weird to me say that simply checking the final result will let you check if the array was sorted. What this actually does is check that when you are done you are in a micro-valid state. It would still be possible to find yourself in a valley where locally elements were sorted, but the element you are searching for was somewhere else unsorted: [1,2,4,5,6,7,3,10] If you search for 3 you will think this is sorted and will not find [3]
Hortitude
Yep, that's why it is called a partial check. It doesn't guarantee that the array is sorted, but it probably is. Only way to fully check is the linear way, but partial checks can be good too.
Justin Peel