Time complexity of binary search for an unsorted array

前端 未结 3 739
青春惊慌失措
青春惊慌失措 2020-12-25 09:19

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

相关标签:
3条回答
  • 2020-12-25 09:29

    The time complexity of linear search is O(n) and that of binary search is O(log n) (log base-2). If we have an unsorted array and want to use binary search for this, we have to sort the array first. And here we have to spend a time O(n logn) to sort the array and then spend time to search element.

    0 讨论(0)
  • 2020-12-25 09:30

    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)

    0 讨论(0)
  • 2020-12-25 09:46

    The answer to your question is in your question itself.

    You are first sorting the list. If you sort your list using quick or merge sort, the complexity becomes o(n*log n). Part - 1 gets over.

    Second part of performing a binary search is done on the 'Sorted list'. The complexity of binary search is o(log n). Therefore ultimately the complexity of the program remains o(n*log n).

    However, if you wish to calculate the median of the array, you don't have to sort the list. A simple application of a linear, or sequential, search can help you with that.

    0 讨论(0)
提交回复
热议问题