Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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