【发布时间】:2021-02-10 13:31:24
【问题描述】:
我正在尝试根据数据创建一个图表,其中我测量了数组中给定数量元素的时间执行。
我已经在 Excel 中制作了一个表格并创建了一个图表,但它不适合,因为我的程序的时间复杂度是 O(logn),而且图表的结果是线性的。
当我刷新浏览器时,给定数量的元素的执行时间非常接近,每个执行的时间都不同,比方说有 40-80 毫秒的差异。
我做错了什么,图表的时间复杂度与它的时间复杂度不同?
<script>
//generate array
var size = 10000000; // number of elements
var max = 10000; // max value in the array
var tab = [];
for(k=0; k<size; k++)
{
los = Math.floor(Math.random() * max) + 1;
tab[k] = los;
}
tab.sort(function(a, b) {return a - b;}); //
//------------------------------------------------
function count(tab, w, n)
{
idMin = first(tab, 0, n-1, w, n);
if (idMin == -1){return idMin};
idMax = last(tab, idMin, n-1, w, n);
amount = idMax-idMin+1;
return amount;
}
function first(tab, l, p, w, n)
{
if(l <= p)
{
mid = Math.floor((l+p)/2);
if((mid == 0 || w > tab[mid-1])&&(tab[mid] == w))
{
return mid;
}
else if(w > tab[mid])
{
return first(tab, (mid+1), p, w, n);
}
else
{
return first(tab, l, (mid-1), w, n);
}
}
return -1;
}
function last(tab, l, p, w, n)
{
if(l <= p)
{
mid2 = Math.floor((l+p)/2);
if((mid2 == n-1 || w < tab[mid2+1]) && (tab[mid2] == w))
{
return mid2;
}
else if(w < tab[mid2])
{
return last(tab, l, (mid2-1), w, n);
}
else
{
return last(tab, (mid2+1), p, w, n);
}
}
}
w = 49; //searching value
n = tab.length;
console.time("test");
how_many = count(tab, w, n);
console.timeEnd("test");
if(how_many == -1)
{
document.write("The value "+w+" showed 0 times<br/>");
}
else
{
document.write("The value "+w+" showed "+how_many+" times<br/>");
}
</script>
【问题讨论】:
标签: javascript time-complexity diagram