Last active
July 1, 2016 22:54
-
-
Save williamrjribeiro/c8ae00cd550374e5dc7d59ffddae66af to your computer and use it in GitHub Desktop.
Linear Time Array Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sumArrayLinear(A, start, end){ | |
end = (end >= A.length ? A.length - 1: end); // avoid Out of Bounds | |
var total = 0; | |
for(start; start <= end; start++) | |
total += A[start]; | |
return total; | |
} | |
var arr = [2,5,7,4,2,4,3,3,2,1,8,6,9,7,5,4,2,5,6,7,9,0,8,5,3,2,4,5,6,7,8,5,6], | |
arrSum = []; | |
for(var i = 0, l = arr.length - 5; i < l; i++) // loops 28 times | |
arrSum.push(sumArrayLinear(arr, i, i + 4)); // inner loop 5 times | |
// Total: 28 x 5 = 140 operations | |
console.log("arrSum: "+arrSum); | |
// arrSum: 20,22,20,16,14,13,17,20,26,31,35,31,27,23,22,24,29,27,30,29,25,18,22,19,20,24,30,31 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment