Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0aea53

Browse files
Big o notation
1 parent 707f24b commit d0aea53

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎bigOnotation.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Constant runtime - Big O Notation: "O (1)"
2+
function log(array) {
3+
console.log(array[0]);
4+
console.log(array[1]);
5+
}
6+
7+
log([1, 2, 3, 4]);
8+
log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
9+
10+
// Linear runtime - Big O Notation: "O (n)"
11+
function logAll(array) {
12+
for (var i = 0; i < array.length; i++) {
13+
console.log(array[i]);
14+
}
15+
}
16+
17+
logAll([1, 2, 3, 4, 5]);
18+
logAll([1, 2, 3, 4, 5, 6]);
19+
logAll([1, 2, 3, 4, 5, 6, 7]);
20+
21+
// Exponential runtime - Big O Notation: "O (n^2)"
22+
function addAndLog(array) {
23+
for (var i = 0; i < array.length; i++) {
24+
for (var j = 0; j < array.length; j++) {
25+
console.log(array[i] + array[j]);
26+
}
27+
}
28+
}
29+
30+
addAndLog(["A", "B", "C"]); // 9 pairs logged out
31+
addAndLog(["A", "B", "C", "D"]); // 16 pairs logged out
32+
addAndLog(["A", "B", "C", "D", "E"]); // 25 pairs logged out
33+
34+
// Logarithmic runtime - Big O Notation: O (log n)
35+
function binarySearch(array, key) {
36+
var low = 0;
37+
var high = array.length - 1;
38+
var mid;
39+
var element;
40+
41+
while (low <= high) {
42+
mid = Math.floor((low + high) / 2, 10);
43+
element = array[mid];
44+
if (element < key) {
45+
low = mid + 1;
46+
} else if (element > key) {
47+
high = mid - 1;
48+
} else {
49+
return mid;
50+
}
51+
}
52+
return -1;
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /