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.
use standard binary search
x
, making sure choose even indices comparison. (using indices crucial, because elements still in order.)if
x
in array @ index, found. if not, find 2 elementsm
,n
suchm < x < n
,index(n) - index(m) == 2
. means if array still sorted,x
have element betweenm
,n
(if in array).consider element @ index between
m
,n
- cally
. if elementx
in original array, must have been swappedy
when creating shuffled array.perform second binary search
y
, again ensuring choose even indices comparison. step 2, find 2 elementsm'
,n'
suchm' < y < n'
,index(n') - index(m') == 2
. if array still sorted, elementy
element betweenm'
,n'
.the element between
m'
,n'
must whichever element swappedy
, , therefore whatever element betweenm
,n
. if value notx
,x
not exist in array.
Comments
Post a Comment