简体   繁体   中英

Given an array part is sorted part is not, How to find a particular element?

To be honest this was an interview question. I know if the array is totally sorted then I could use binary search which is O(logN). But now the condition is:

  1. Some part is sorted while others are not.
  2. We don't know which is part is sorted nor how long this part is.

I could only think of a full array scan solution which is O(N). But interviewer said there is a O(logN) solution. Please help.

Either you are not telling the full question, or your the interviewer is totally wrong. Here is an example that fits your description.

[1, 2, 3, 4, 5, 9, -1, 8, 0, 8, -2, 4, 7, 6]

As you see the first 5 elements are sorted. But it does not help you at al to locate where the 6 is in my array. You will still need O(n) to find an element.

Putting your question to an extreme, what if the sorted part consists of 2 elements and unsorted part is n-2 elements? Can he still search it in O(log n ) ?

Just an advise to you. Once you hear something that you can't actually believe, ask a person to explain you an idea and think of a counter example that makes this idea useless.

The interviewer is wrong. Without knowing where the sorted part begins, and its size, you cannot search it in O(logN).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM