-1

Code snippet

Following is the delete function definition to delete all the occurrences of an element x in an int type array named a in C language!

void delete(int x)
{
 for(int i=0 ; i<size ; i++)
 {   
   if (a[i] == x)
   {   
     for(int j=i+1;j<size;j++)
     {
      a[j-1]=a[j];
     }
      size--; 
   }  /* end of if */
 }   /*end of outer for*/
}

The time complexity of above code is coming out to be O(n2) , quadratic complexity .

My question : The outer for loop will run n times and the number of times the inner for loop runs would depend on the number of occurrences of x then how is the complexity coming out to be O(n2) ?

varunsinghal65
  • 536
  • 1
  • 5
  • 20
  • 3
    What if `x = 1;` and `a[] = {1,1,1,1,1,1,1,1,1};` ? – Santosh A Dec 19 '14 at 08:24
  • `a is statically declared` that doesn't have anything to do with time complexity and you have written the function to delete all occurrence of a number. `So time complexity for the above set of inputs is O(n^2).` – Santosh A Dec 19 '14 at 09:29

1 Answers1

1

In the worst case analysis, we calculate upper bound on running time of an algorithm. We must know the case that causes maximum number of operations to be executed.

We evaluate the situation when values in if-else conditions cause maximum number of statements to be executed.

Therefore the worst case can happen when the array contains all the similar element and the element to be deleted is the same.

In such case the 'if' executes for all the values of outer for loop. hence runs in O(N) time.

considering the inner for loop:

For array of SIZE = size in worst case,

for 1st pass the inner loop executes n-1 times and

for 2nd pass loop executes n-2 times and so on....

c*((n-1)+(n-2)+.....+1)) where c is the time required for assign statement in inner for loop. Why it is so ? because each time one element is getting removed after one iteration.

Considering K is the constant time for assigning i,j.

c1 is the cost of checking the loop condition and increment and decrement operation.

Then,

c*((n-1)+(n-2)+....+1)+K+c1*(size-1)

(n-1)+(n-2)+.....+1 = n*(n-1)/2.

cn(n-1)/2+k+c1*(size-1) = 1/2*c(n^2-n)+c(n-1)+k = upper bound O(n^2).

Hence the time complexity turns out to be O(n^2).

Manjunath N
  • 1,365
  • 11
  • 22