SDj - 5 months ago 51

C Question

I made this piece of code written in C which takes too long to run. Is there any way to improve it?

What i want to do is to sum the values of each row and save the value in a vector. In this code, i1 is the value containing the row locations of a matrix, the columns and the associated value. i1 is not sorted.

`while(a < 2*var)`

{

for (int c=0; c < 2*var; c++)

{

if (i1[c][0] == a)

{

diag[b] += i1[c][2];

}

}

a = a+1;

b = b+1;

}

Any idea or suggestion will be greatly appreciated. Thank you.

Solution:

`for (int c=0; c < 2*var; c++)`

{

diag[i1[c][0]] += i1[c][2];

}

Answer

As `b = a + const`

, you could simply use `diag[i1[c][0] + const] += i1[c][2]`

and reduce the complexity from O(N^{2}) to O(N).