我希望尽可能少使用正式定义和简单的数学语言。
我希望尽可能少使用正式定义和简单的数学语言。
function lineerSearch() {
init();
var t = timer('lineerSearch benchmark');
var input = this.event.target.value;
for(var i = 0;i<unsortedhaystack.length - 1;i++) {
if (unsortedhaystack[i] === input) {
document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return unsortedhaystack[i];
}
}
}
function binarySearch () {
init();
sortHaystack();
var t = timer('binarySearch benchmark');
var firstIndex = 0;
var lastIndex = haystack.length-1;
var input = this.event.target.value;
//currently point in the half of the array
var currentIndex = (haystack.length-1)/2 | 0;
var iterations = 0;
while (firstIndex <= lastIndex) {
currentIndex = (firstIndex + lastIndex)/2 | 0;
iterations++;
if (haystack[currentIndex] < input) {
firstIndex = currentIndex + 1;
//console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
} else if (haystack[currentIndex] > input) {
lastIndex = currentIndex - 1;
//console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
} else {
document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
console.log(document.getElementById('result').innerHTML);
t.stop();
return true;
}
}
}
O(n)
表示:
如果一个算法的时间/空间复杂度为O(n),则称该算法的运行时间/空间是线性的或O(n)。简而言之,这意味着随着输入规模的增加,其运行时间/空间最多呈线性增长(source)。
而O(n log n)
则表示:
如果T(n) = O(n log^k n)(其中k是正常数),则称该算法以准线性时间/空间运行;当k=1时,则称该算法以线性对数时间/空间运行(source)。
然而,通常这种轻松的措辞通常用于量化(针对最坏情况)一组算法在其输入大小增加方面与另一组算法的行为方式相比。要比较两类算法(例如,O(n log n)和O(n)),应分析两类算法在最坏情况下随着其输入大小(即n)的增加而表现如何;当n趋近于无穷大时分析n。 在上面的图像中,big-O
表示绘制函数渐近最小上界之一,并且不是指集合O(f(n))
。O(n log n)
和O(n)
时,可以看到在某个输入后,O(n log n)
(绿线)增长速度比O(n)
(黄线)更快。这就是为什么(对于最坏情况),O(n)
比O(n log n)
更可取的原因,因为您可以增加输入大小,而前者的增长率会比后者慢。仅仅为了以快速简单的方式表达算法的复杂性。 大O符号存在的目的是解释任何给定算法的最佳、最坏和平均时间复杂度。它们只是可能问题实例大小的数值函数。
换句话说,精确地使用这些函数非常困难,因为它们往往会:
使用大O符号以简单的上限和下限时间复杂度函数来交流,证明这是更容易的。大O符号通过忽略不影响算法比较的细节层次来简化我们的分析。 大O符号忽略了乘法常数之间的差异。在大O分析中,函数f(n)=2n和g(n)=n是相同的。
https://mimoza.marmara.edu.tr/~msakalli/cse706_12/SkienaTheAlgorithmDesignMan ual.pdf