如何计算简单搜索的复杂性

how to calculate complexity of a simple search

本文关键字:简单 搜索 复杂性 计算 何计算      更新时间:2023-10-16

我有一个包含 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 个元素。