algorithmsumbig-o

Summing an Array and Big O Notation


How to find an algorithm for calculating the sum value in the array??

Is is Something like this?

Algorithm Array Sum
Input: nonnegative integer N, and array A[1],A[2],...,A[N]
Output: sum of the N integers in array A
Algorith Body:
j:=1
sum:=0
while j<N
      sum := sum + a[J]
      j:=j+1
  end while
end Algorithm Array Sum

And how I can relate it with the running time of the algorithm by using O-Notation

This is the past year exam and I need to make revision for my exam.

Question
An Array A[] holding n integer value is given
1.Give an algorithm for calculating the sum of all the value in the array
2.Find the simplest and best O-notation for the running time of the algorithm.


Solution

  • The question is to find the sum of all the values so iterate through each element in the array and add each element to a temporary sum value.

    temp_sum = 0
    for i in 1 ...array.length
        temp_sum = temp_sum + array[i]
    

    Since you need to go through all the elements in the array, this program depends linearly to the number of elements. If you have 10 elements, iterate through 10 elements, if you have a million you have no choice other than to go through all the million elements and add each of them. Thus the time complexity is Θ(n).

    If you are finding the sum of all the elements and you dont know any thing about the data then you need to look at all the elements at least once. Thus n is the lowerbound. You also need not look at the element more than once. n is also the upper bound. Hence the complexity is Θ(n).

    However if you know something about the elements..say you get a sequency of n natural numbers, you can do it in constant time with n(n+1)/2. If the data you get are random then you have no choice but do the above linear time algorithm.