Search code examples
algorithmsearchbinary-searchpreconditions

Binary Searching


So, I want to understand more about binary searching, cause I don't really understand. Binary search requires a precondition that an array is sorted. I got that right? It seems like a method should check this precondition and throw an exception if it is not met. But, why is checking the precondition a bad idea?


Solution

  • It's a bad idea because checking the data is sorted takes n steps. The whole search is about log(n) steps.
    If you're going to check, you might as well do a linear search.