Table of contents
Before diving into implementing algorithms, it's essential to grasp how to evaluate their effectiveness. This blog post will delve into the concept of Big-O notation, which is crucial for analyzing time and space complexity. By the end of this read, you'll be equipped to assess an algorithm's implementation in terms of both execution time and memory usage.
Big-O notation measures an algorithm's worst-case complexity. Here, (n) denotes the number of inputs. The key question posed by Big-O is: “What happens as (n) approaches infinity?” Understanding Big-O notation is crucial when implementing algorithms, as it reveals their efficiency.
Common Big-O complexities
The upcoming sections demonstrate these common time complexities through straightforward examples.
1. O(n): (O(n)) denotes linear time complexity, applying to algorithms that perform (n) operations in the worst-case scenario. A typical example of an (O(n)) algorithm is printing numbers from 0 to (n-1), as illustrated below:
function LinearNum(n){
for (var i =0; i <n; i++){
console.log(i)
}
}
NB: O(1) is holy.
O(1) does not change with respect to input space. Hence, O(1) is referred to as being constant time.
- O(n²): (O(n²)) represents quadratic time complexity. Examples of such complexities are provided below:
function quadratic(n){
for (var i = 0; i<n; i++){
console.log(i);
for (var j =i; j<n; j++){
console.log(j);
}
}
}
3. O(n³): (O(n³)) represents cubic time complexity. Examples of such complexities are provided below:
function cubic(n){
for(var i = 0; i < n; i++){
console.log(i);
for(var j =i; j<n; j++){
console.log(j);
for(var k = j; k < n; k++){
console.log(k);
}
}
}
}
- Logarithmic time complexities: An example of an algorithm with logarithmic time complexity is printing elements that are powers of 2 between 2 and n. The efficiency of logarithmic time complexities becomes evident with large inputs, such as a million items. Although n is a million,
Logarithmic
will print only 19 items because log2(1,000,000)=19.9315686\log_2(1,000,000) = 19.9315686log2(1,000,000)=19.9315686. The code demonstrating this logarithmic behavior is as follows:
function Logarithmic(n) {
for (var i = 2; i <= n; i = i * 2) {
console.log(i);
}
}
Conclusion
Thanks a lot for reading, and I hope you now have a better understanding of algorithmic time complexity and Big-O notation. For more detailed information, please check out my other additional resources on algorithm analysis. And don't forget to hit a 👍 if you found this article helpful. Happy coding! 🎉