Data Structures, Algorithms, & Applications in Java
Chapter 17, Exercise 23

Assume that the adjacency matrix of an n vertex digraph is stored in the boolean matrix a[n + 1][n + 1] with A(i,j) stored in a[i][j]. The number of edges is the number of array entries that have the value true.

The code is given below. A test program and output appear in the file NumberOfEdges.*.
public int numberOfEdges()
{
   int count = 0;      // default initial value is 0
   for (int i = 1; i < a.length; i++)
      for (int j = 1; j < a.length; j++)
         if (a[i][j])
            // directed edge (i,j) exists
            count++;

   return count;
}



The if statement in numberOfEdges is executed n2 times and no statement has a greater total cost. Therefore, the complexity of numberOfEdges is O(n2).