算法中的步数

时间:2013-05-21 07:25:44

标签: algorithm complexity-theory

此算法的步数是多少?

SequentialSearch(a,x,n)
{
    i=n;
    a [0]=x;
    while(a [i]!= x) do
        i = i-1
    return i
}

请在此提及每一步的计数。谢谢!

3 个答案:

答案 0 :(得分:2)

查找步数的程序

首先定义步骤:

int mean(int a[], size_t n)

{
int sum = 0;                 // 1 step * 1
for (int i = 0; i < n; i++)  // 1 step * (N+1)
    sum += a[i];             // 1 step * N
return sum;                  // 1 step * 1
}

接下来根据N确定步骤的频率:

#include "json2.js" // jshint ignore:line
var script_file = File($.fileName); // get the location of the script file
var script_file_path = script_file.path; // get the path

var file_to_read = File(script_file_path + "/unique-job-id.json");
var my_JSON_object = null; // create an empty variable
var content; // this will hold the String content from the file
  if(file_to_read !== false){// if it is really there
    file_to_read.open('r'); // open it
    content = file_to_read.read(); // read it
    my_JSON_object =  JSON.parse(content);// now evaluate the string from the file
    //alert(my_JSON_object.arr[1]); // if it all went fine we have now a JSON Object instead of a string call length
    var theComposition = app.project.item(1);
    var theTextLayer = theComposition.layers[1];
    theTextLayer.property("Source Text").setValue(my_JSON_object.arr[2]);
    file_to_read.close(); // always close files after reading
    }else{
    alert("Error reading JSON"); // if something went wrong
  }

添加步骤:1 +(N + 1)+ N + 1

减少:2N + 3

抛弃那些与N一起成长并且你已经完成的因素:O(N)

答案 1 :(得分:1)

我希望这就是你要找的东西:

while (a[i] != x) i = i-1;

最坏的情况:将扫描整个数组,从a[n]a[0] = O(n)

平均情况:将扫描半数组O(n / 2)= O(n)

复杂性是O(n)

答案 2 :(得分:1)

以下是您的步数分析:

SequentialSearch(a,x,n)
{
   i=n;    // 1 assignment operation 
   a [0]=x; // 1 assignment operation 
    while(a [i]!= x) do  // n number of comperison (worst case)
       i = i-1 // n number of decrement operation (worst case)
    return i // 1 return 
}

在最坏的情况下,您有2n + 3次操作。由于您的操作次数与输入数组大小(n)呈线性关系,因此在最坏的情况下。因此算法的运行时复杂度为O(n)