搜索算法及其复杂性

编程入门 行业动态 更新时间:2024-10-24 05:16:39
本文介绍了搜索算法及其复杂性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人问我这个问题,在接受采访时:假定一个的无限的是排序整数数组。你将如何寻找该数组的整数?什么是时间复杂度? 我猜到了由无限意味着面试官是,我们不知道N,其中n是数量最多的数组中的索引值。 我给了以下的答案:

I was asked this question in an interview: Assume an infinite array of integers which is sorted. How would you search for an integer in this array? What would be time complexity? I guessed what the interviewer meant by infinite is that we dont know the value of 'n', where n is the index of the largest number in the array. I gave the following answer:

SEARCHINF(A,i,x){ // Assume we are searching for x if (A(1) > x){ return } if(A(i) == x){ return i; } else{ low = i; high = power(2,i); if (A(i)>x){ BINARY-SEARCH(A,low,high); } else{ SEARCHINF(A,high,x); } }// end else }// end SEARCHINF method

这会发现在边界(低和高)(登录X + 1),在最坏的情况下,正值的排序从1开始和随后的数字是因之。 然后二进制搜索要求:

This will find the bound(low and high) in (log x + 1) time in the worst case, when the sorted numbers start from 1 and subsequent numbers are consequent. Then the binary search requires:

O( log {2^(ceil(log x)) - 2^(floor(log x))} )

这是正确的?如果正确的话,可以在此进行优化?

Is this correct? If correct, can this be optimized?

推荐答案

使用双索引的方法,直到你通过它,然后二进制搜索的区域,你只跳过了(它是什么样子的伪code是尝试做),花费的时间应为O(log 2 n),其中n是您正在搜索的项目的索引。

Using the method of double your index until you pass it, then binary search the region you just jumped over (what it looks like your pseudocode is trying to do), the time spent should be O(log2 n) where n is the index of the item you are searching for.

它会带你(日志 2 N)试图找到正确的区域,然后((登录 2 N) - 1)试图找到 X 的区域内(因为你已经从0到n / 2搜查,你只需要搜索N /第2..N)。因此,为O(log 2 N +日志 2 N - 1)= O(日志 2 N)

It will take you (log2 n) tries to find the correct region, and then ((log2 n) - 1) tries to find x within that region (since you already searched from 0..n/2, you only need to search n/2..n). Therefore, O(log2 n + log2 n - 1) = O(log2 n).

但是,如果无限阵列不包含 X 或大于 x值,你会从来不知道,因为你永远搜索

However, if the "infinite array" does not contain x or any value greater than x, you will never know, because you will search forever.

更多推荐

搜索算法及其复杂性

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

发布评论

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

>www.elefans.com

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