Array search

Consider the problem of finding an element x x in an array of size n n . In which of the following cases can we find the element x x in O ( log n ) O(\log n) time?

A) Array is sorted.

B) Array is sorted and is rotated by k k . The value of k k is known.

C) Array is sorted and is rotated by k k . The value of k k is unknown.

D) Array is not sorted.

All A A only A A and B B A , B A, B and C C

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

展豪 張
Mar 23, 2016

A nice question! (liked)
Answer is A , B , C A,B,C .
For A A simply use binary search. It's O ( log n ) O(\log n) .
For B B rotate it back first. Then use binary search. It's O ( 1 ) + O ( log n ) = O ( log n ) O(1)+O(\log n)=O(\log n) .
For C C use binary search to find out value of k k first. Then rotate it back. Then use binary search. It's O ( log n ) + O ( 1 ) + O ( log n ) = O ( log n ) O(\log n)+O(1)+O(\log n)=O(\log n) .

Can you explain how'll you find k using binary search in C?

Pranjal Jain - 5 years, 2 months ago

Log in to reply

Since the array is sorted then rotated, it consists of two sorted array and there is one point in the middle that array[n]>array[n+1].
For example, it is like this:
Sorted: 1 2 3 4 5 6 7 8 9
Rotated: 5 6 7 8 [9 1] 2 3 4
We first obtain the values of first and last element: 5 4
Then we preform the binary search. If it is larger replace it with the first and vice versa.
Example:
5 \color{#3D99F6}5 6 7 8 9 \color{#D61F06}9 1 2 3 4 \color{#3D99F6}4 [5 4]
5 6 7 8 9 \color{#3D99F6}9 1 2 \color{#D61F06}2 3 4 \color{#3D99F6}4 [9 4]
5 6 7 8 9 \color{#3D99F6}9 1 \color{#D61F06}1 2 \color{#3D99F6}2 3 4 [9 2]
5 6 7 8 9 \color{#3D99F6}9 1 \color{#3D99F6}1 2 3 4 [9 1]
So we find the value of k k

展豪 張 - 5 years, 2 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...