如何计算简单搜索的复杂性
how to calculate complexity of a simple search
我有一个包含 n 个元素的数组。现在我需要搜索一个元素 x。这是程序
int x[100],i,s;
cout<<"Enter how many number of element you have";
cin>>n;
for(i=0;i<n;i++)
{
cin>>x[i];
}
cout<<"Enter element which you want to search";
cin>>s;
for(i=0;i<n;i++)
{
if(x[i]==s)
{
cout<<"Item found in position"<<i;
break;
}
}
这个程序的时间和空间复杂度是多少?
Space:
x[100] = 200 bytes
n = 1 byte
s = 1 byte
==================
Total = 202 bytes
正确吗?
时间复杂度:请帮我弄清楚
最佳情况(如果 x 匹配 n 的第一个元素)复杂性?最坏的情况(如果 x 匹配 n 的最后一个元素或不匹配)复杂性?
时间复杂度:
Time complexity is nothing but number of comparisons done by computer in your code.
因此,当您搜索数组时,您实际上会进行 n 个比较。将数组中的每个元素与输入元素进行比较。因此,在这种情况下:
最佳情况:O(1) - 在第一次比较中找到元素。
最坏情况:O(n) - 表示您必须搜索所有元素,并在数组的最后一个位置找到该元素。
空间复杂度:
Normally, this is seen in terms of numbers of elements in the array rather
then the total size taken by these elements. This is done because size of data
types differ on various architectures but number of elements is dependent on the
problem and not the machine.
因此,在您的情况下:
空间复杂度 = "n"..由于数组中存在 n 个元素。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- (C++)分析树以计算返回错误值的简单算术表达式
- 有根的二进制搜索树.保留与其父级的链接
- 我的简单if-else语句是如何无法访问的代码
- 使用简单类型列表实现的指数编译时间.为什么
- 在C++中搜索嵌套多映射值
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 用于二分搜索的错误简单功能(C++)
- 简单的二进制搜索树非递归添加功能
- Netbeans 7.4 C++简单的 hello world 错误构建失败尝试了 Google 搜索结果前 2 页上的
- 简单的C++数组搜索
- 简单的二叉搜索树.分段错误
- 如何计算简单搜索的复杂性
- 如何以最佳、最简单的方式在文件中搜索
- c++中简单的通配符搜索算法
- 调试使用广度优先搜索(BFS)的简单图算法
- 试图做一个简单的搜索和计数输入字在c++
- 为什么这个简单的二进制搜索虽然输出了正确的中值,却没有返回正确的中值
- 哪些情况会导致对c++代码进行原始变量的简单搜索失败?