algorithm - Searching for an element in log(n) time -


i came across following question:

suppose modify given sorted list of 4n distinct numbers follows:

keep elements in positions (positions 2, 4, 6, ... 4n) are. form n disjoint pairs (i,j) on odd numbered positions = 2k+1 k = 0 n−1 , j = 2k+1 k = n 2n−1.

now swap elements in positions , j every such pair. (i.e. every element in odd numbered position in first half of array swapped element in odd numbered position in second half of array. no element involved in more 1 swap (i.e. swaps disjoint). don’t know these (i,j) pairs except element in odd numbered position in first half of array swapped element in odd numbered position in second half. given element x, explain how can determine whether or not x in (new reshuffled) array in o(logn) time.

honestly, not sure how approach one. given x, can search whether exists @ numbered position using binary search. numbers in odd positions no longer sorted.

any appreciated. thanks!

you can determine whether element x in new (shuffled) set doing 2 binary searches. key here odd elements act "keys" each other, since have been swapped in disjoint pairs.

  1. use standard binary search x, making sure choose even indices comparison. (using indices crucial, because elements still in order.)

  2. if x in array @ index, found. if not, find 2 elements m , n such m < x < n , index(n) - index(m) == 2. means if array still sorted, x have element between m , n (if in array).

  3. consider element @ index between m , n - call y. if element x in original array, must have been swapped y when creating shuffled array.

  4. perform second binary search y, again ensuring choose even indices comparison. step 2, find 2 elements m' , n' such m' < y < n' , index(n') - index(m') == 2. if array still sorted, element y element between m' , n'.

  5. the element between m' , n' must whichever element swapped y, , therefore whatever element between m , n. if value not x, x not exist in array.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -