Time complexity of binary search for an unsorted array

user1521306 picture user1521306 · Apr 9, 2013 · Viewed 40.7k times · Source

I am stuck up with two time complexities. To do a binary search with sorted array is O(logN). So to search an unsorted array we have to sort it first so that becomes O(NlogN). So then we can perform binary search which gives the complexity as O(N) but I have read that it could be O(NlogN). Which is correct?

Answer

LuiNova picture LuiNova · Apr 9, 2013

Binary Search is for "Sorted" lists. The complexity is O(logn).

Binary Search does not work for "un-Sorted" lists. For these lists just do a straight search starting from the first element; this gives a complexity of O(n). If you were to sort the array with MergeSort or any other O(nlogn) algorithm then the complexity would be O(nlogn).

O(logn) < O(n) < O(nlogn)