Skip to content

Instantly share code, notes, and snippets.

@williamrjribeiro
Last active July 1, 2016 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamrjribeiro/c8ae00cd550374e5dc7d59ffddae66af to your computer and use it in GitHub Desktop.
Save williamrjribeiro/c8ae00cd550374e5dc7d59ffddae66af to your computer and use it in GitHub Desktop.
Linear Time Array Sum
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