I am a beginner of C++ and learning Algorithm Analysis:
I am writing a method which return a row number of a 2d array has most 1's , each rows from the input array are all sorted and hits 0 when all 1's are sort to the front like

Your question is pretty vague but I would think going through and counting the number of assignments, indexes, increments (which should be pre- not postincrements btw) on the worst case and average scenarios would be the way to go.
–
Matt PhillipsMar 7 '12 at 13:31

Do you want to analyze it and calculate its cost? Or do you want to run it and measure its cost?
–
David SchwartzMar 7 '12 at 13:32

2 Answers
2

This is how you can evaluate the runtime complexity of your code.For your code, the worst case complexity would be the size of your matrix (i.e. if your code compiles) after you make the end false when row and column equal the size of your matrix.

I don't think it is true [the complexity is the size of the matrix] in here. I think it is actually O(infinity), if I understood correctly - the stopping condition is once the value of the entree is not 0/1, which is not guaranteed [assume the matrix lays within a memory of size 2^n * 2^m which was just memset()ed to 0. Though I might be missing something...
–
amitMar 7 '12 at 13:33

I already mentioned in the answer that the complexity is only after he makes end false when row and column equal the size of matrix.
–
Pulkit GoyalMar 7 '12 at 13:35

is roughly the same, but you can see easy how often a loop/statement is executed(that is what you actually wont). The outer loop is ran rowCount times the inner at most colCount times(average case depends) for itself but that rowCount times.

Then look what statement costs how much. And multiply it with the number of times it is executed(average-/worst case what you like).

Thanks for the advice. However, my target is making the running time cost to O(N). That will be O(N^2) if there is a double "for" loop.
–
Choi Shun ChiMar 8 '12 at 6:41

If rowCount and colCount is independent you cant say it's O(N^2). Then it is O(NM). Best solution for that problem would be O(Nlog(M)) when you use a matrix. Though, with a simple array of numbers count O(N) is possible. However, if N is the number of fields in your matrix, the problem is already in O(N)
–
x539Mar 8 '12 at 10:49