在无限长的排序数组中查找元素

编程入门 行业动态 更新时间:2024-10-08 06:26:15
本文介绍了在无限长的排序数组中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个具有正整数和负整数的无限长度排序数组.在其中找到一个元素.

Given an infinite length sorted array having both positive and negative integers. Find an element in it.

编辑数组中的所有元素都是唯一的,并且数组在正确的方向上是无限的.

EDIT All the elements in the array are unique and the array in infinite in right direction.

有两种方法:

将索引设置在100位置,如果要查找的元素较少,则在前100项中进行二分查找,否则在位置200设置下一个索引.这样,继续将索引增加100,直到找到该项更大.

Set the index at position 100, if the element to be found is less, binary search in the previous 100 items, else set the next index at position 200. In this way, keep on increasing the index by 100 until the item is greater.

将索引设置为 2 的幂.首先将索引设置在位置 2,然后是 4,然后是 8,然后是 16,依此类推.再次从位置 2^K 到 2^(K + 1) 进行二分搜索,其中 item 介于两者之间.

Set the index in power of 2. First set the index at position 2, then 4, then 8, then 16 and so on. Again do the binary search from position 2^K to 2^(K + 1) where item is in between.

在最好和最坏的情况下,这两种方法中哪一种更好?

Which of the two approaches will be better both in best case and worst case?

推荐答案

第一种方法将在元素的索引中线性 (O(k) where k是元素的索引).实际上,您将需要 k/100 次迭代才能找到大于搜索元素的元素,即 O(k).

The first approach will be linear in the index of the element (O(k) where k is the index of the element). Actually, you are going to need k/100 iterations to find the element which is greater than the searched element, which is O(k).

第二种方法将在同一索引中进行对数.O(logk).(其中 k 是元素的索引).在这里,您将需要 log(k) 迭代,直到找到更高的元素.然后 2^(i-1), 2^i(其中 i 是迭代次数)之间的二分搜索,也将是对数的, 总计 O(logk)

The second approach will be logarithmic in the same index. O(logk). (where k is the index of the element). In here, you are going to need log(k) iterations until you find the higher element. Then binary search between 2^(i-1), 2^i (where i is the iteration number), will be logarithmic as well, totaling in O(logk)

因此,第二种更有效.

更多推荐

在无限长的排序数组中查找元素

本文发布于:2023-11-29 06:11:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序数   组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!