Skip to content

Instantly share code, notes, and snippets.

@coderwurst
Last active January 20, 2020 16:45
Show Gist options
  • Save coderwurst/66515e2c39f1a5d1932ac13105540264 to your computer and use it in GitHub Desktop.
Save coderwurst/66515e2c39f1a5d1932ac13105540264 to your computer and use it in GitHub Desktop.
Big O Notation Examples
// Calculate the sum of all numbers from 1 - 10
// O(n)
function addUpToOne(n) {
return n * (n +1) / 2;
}
var timeOne = performance.now();
addUpToOne(10000000);
var timeTwo = performance.now();
console.log(`Time taken 2: ${(timeTwo - timeOne) / 1000} seconds`)
// O(1)
function addUpToTwo(n) {
return n * (n +1) / 2;
}
var timeOne = performance.now();
addUpToTwo(10000000);
var timeTwo = performance.now();
console.log(`Time taken 2: ${(timeTwo - timeOne) / 1000} seconds`)
// O(n)
function countUpAndDown(input) {
for (i=0; i<= input; i++) {
console.log(i)
}
}
countUpAndDown(10);
// O(n^2)
function printAllPairs(input) {
for ( i = 0; i < input; i++) {
for (j = 0; j < input; j++) {
console.log(i, j)
}
}
}
printAllPairs(10);
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment