[英]how to do binary search on array which is the numbers on even indexes are ascending and the numbers on odd indexes are descending
how to do binary search on array which is the numbers on even indexes are ascending and the numbers on odd indexes are descending example the array {-3,10,0,9,5,0,7,-1} and i want to find a number: x=5如何对数组进行二进制搜索,偶数索引上的数字是升序的,奇数索引上的数字是降序的,例如数组 {-3,10,0,9,5,0,7,-1} 我想找一个数字:x=5
i think i should do binary search on even indexes alone, and on odd indexes alone我想我应该单独对偶数索引和奇数索引进行二进制搜索
You can use two binary searches, one for the increasing and decreasing values each.您可以使用两个二进制搜索,一个用于递增和递减的值。 There will be a few simple modifications:
会有一些简单的修改:
[0, n-1]
(where n
is the length of array).[0, n-1]
(其中n
是数组的长度)。 The opening and closing limit will be different for the descending and ascending values respectively.low = mid + 1
or high = mid - 1
, you'll use low = mid + 2
and high = mid - 2
so that the parity of the middle index doesn't change during the search.low = mid + 2
和high = mid - 2
而不是调整low = mid + 1
或high = mid - 1
,这样中间索引的奇偶性在搜索过程中不会改变。 Since this is a simple task, I'll leave the formal algorithm for the reader to figure out.由于这是一项简单的任务,我将把正式的算法留给读者去弄清楚。
You are right, you can perform two separate binary searches.你是对的,你可以执行两个单独的二进制搜索。 One on
一上
(-3,0,5,0,7)
and the other on另一个在
(-1,0,9,10).
As regards the implementation, you can use a standard algorithm and至于实现,您可以使用标准算法和
replace all indexes by their double ( i
becomes 2i
) for the first search;将所有索引替换为第一次搜索的双精度(
i
变为2i
);
replace all indexes by m-2i
where m
is n
or n-1
, whichever is odd for the second search.用
m-2i
替换所有索引,其中m
是n
或n-1
,以第二次搜索的奇数为准。
You cannot do with a single search, replacing the even indexes by 2i
and the odd ones by m-2i
because there is no guarantee that this would correspond to a growing sequence (eg (-3,-1,0,0,5,9,7,10)
).您不能通过单个搜索来完成,用
2i
替换偶数索引,用m-2i
替换奇数索引,因为不能保证这会对应于一个增长的序列(例如(-3,-1,0,0,5,9,7,10)
)。 A preliminary merge is required, taking linear time.需要进行初步合并,这需要线性时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.