总结
豆包 AI 助手文章总结
首页 > 系统教程 > LINUX > 正文

算法——跳跃搜索

WBOY
发布: 2024-02-16 10:42:02
转载
637人浏览过

算法——跳跃搜索

例如,假设我们有一个大小为n的数组arr []和块(要跳转)的大小m。然后我们搜索索引arr [0],arr [m],arr [2m] ... ..arr [km]等等。一旦我们找到间隔(arr [km]

我们考虑以下数组:(0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610)。数组的长度为16.跳跃搜索将以下列步骤找到55,假设要跳过的块大小为4.

步骤1:从索引0跳转到索引4;
步骤2:从索引4跳转到索引8;
步骤3:从索引8跳转到索引16;
步骤4:由于索引16处的元素大于55,因此我们将返回一步到索引9.
步骤5:从索引9执行线性搜索以获取元素55。
要跳过的最佳块大小是多少?
在最坏的情况下,我们必须进行n / m跳转,如果最后一个检查值大于要搜索的元素,则对线性搜索进行m-1比较。因此,最坏情况下的比较总数将为((n / m)+ m-1)。当m =√n时,函数((n / m)+ m-1)的值将是最小值。因此,最好的步长是m = √n。

// C++ program to implement Jump Search

#include <bits/stdc++.h>
using namespace std;

int jumpSearch(int arr[], int x, int n)
{
// Finding block size to be jumped
int step = sqrt(n);

// Finding the block where element is
// present (if it is present)
int prev = 0;
while (arr[min(step, n)-1] < x) { prev = step; step += sqrt(n); if (prev >= n)
return -1;
}

// Doing a linear search for x in block
// beginning with prev.
while (arr[prev] < x)
{
prev++;

// If we reached next block or end of
// array, element is not present.
if (prev == min(step, n))
return -1;
}
// If element is found
if (arr[prev] == x)
return prev;

return -1;
}

// Driver program to test function
int main()
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610 };
int x = 55;
int n = sizeof(arr) / sizeof(arr[0]);

// Find the index of 'x' using Jump Search
int index = jumpSearch(arr, x, n);

// Print the index where 'x' is located
cout << "\nNumber " << x << " is at index " << index;
return 0;
}

// Contributed by nuclode
登录后复制

输出:

Number 55 is at index 10

时间复杂度:O(√n)
辅助空间:O(1)

注意:

该查找只针对已经排序的数组。
要跳过的块的最佳大小是O(√n)。这使得跳跃搜索O(√n)的时间复杂度。
跳跃搜索的时间复杂度在线性搜索((O(n))和二进制搜索(O(Log n))之间。
二进制搜索比跳跃搜索更好,但跳转搜索具有我们仅遍历一次的优点(二进制搜索可能需要最多为0(Log n)跳转),考虑要搜索的元素是最小元素或小于最小的)。因此,在跳回成本高昂的系统中,我们使用Jump Search。

以上就是算法——跳跃搜索的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:Linux就该这么学网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号