简体   繁体   English

大O结构

[英]Big O structure

Could anyone point me in the direction to where the Big O notation is in this coding I found?有人能指出我发现的这个编码中大 O 符号的位置吗? http://jsfiddle.net/neekit_rama/6qmoLbex/ http://jsfiddle.net/neekit_rama/6qmoLbex/

<h1 id="title">Array operations with random functions & Big o notation Analysis</h1>

Enter an element to search(1-100):

<input type="text" id="myTextField1"/>

<input type="submit" id="byBtn" value="SearchArray" onclick="StoreArray()"/> <br>

Number of comparisions:<input type="text" id="myTextField2"/>

JavaScript: JavaScript:

function randomIntInc (low, high) {

    return Math.floor(Math.random() * (high - low + 1) + low);

}

function StoreArray(){

var numbers = new Array(100);

for (var i = 0; i < numbers.length; i++) {

    numbers[i] = randomIntInc(1, 100)

}

var element = document.getElementById('myTextField1').value;

    var c=SearchArray(numbers,element);

   var t= document.getElementById('myTextField2');

   myTextField2.value=c;

}

function SearchArray(numbers, Element)

{



    var count=0;

   for (var i = 0; i < numbers.length; i++) {

               count++;

       if(numbers[i]==Element)

       {

           alert('Element found!!.');

           return count;

       }

   }

    alert('Element not found!!.');

    return count;

}

The big-O complexity is O(n) where n is the number of elements in the numbers array.大 O 复杂度为O(n) ,其中nnumbers数组中的元素numbers

O(n) complexity means that the algorithm scales proportionate to n . O(n)复杂度意味着算法的缩放比例与n成正比。 As n gets larger, the function will take a proportionately longer time to execute.随着n变大,该函数将相应地花费更长的时间来执行。

An easy way to figure out the complexity (for a simple loop-based algorithm like this) is by counting the number of comparisons:计算复杂性的一种简单方法(对于像这样的基于循环的简单算法)是通过计算比较次数:

for (var i = 0; i < numbers.length; i++) {
    count++;
    if(numbers[i]==Element)
    ...

The comparison numbers[i]==Element is likely to be the most expensive operation in the loop, and it will be executed numbers.length times in the worst case.比较numbers[i]==Element可能是循环中numbers.length最大的操作,在最坏的情况下会执行numbers.length次。

In the best case, the Element will be the first item in the array, and so the comparison will only be executed 1 time, or O(1) .在最好的情况下, Element将是数组中的第一项,因此比较只会执行 1 次,或O(1) This happens because of the return statement that terminates the loop when a match is found.发生这种情况是因为在找到匹配项时终止循环的return语句。

In the worst case, the Element will be the last item in the array, or will not exist at all, and so the comparison will be executed n times.在最坏的情况下, Element将是数组中的最后一项,或者根本不存在,因此将执行n次比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM