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
1,1,1,0,0
1,1,0,0,0
1,1,1,1,0
1,0,0,0,0
1,1,1,1,1
the method will return 5 from this array and here is the code:
int countone(int a[][]){
int count = 0, column = 0, row = 0, current = 0, max;
bool end = true;
do{
if(a[row][column]==1)
{
current++;
column++;
}
if(a[row][column]==0)
{
column=0;
if(count<current)
{
count = current;
max = row;
current = 0;
}
row++;
if(a[row][column] != 1 && a[row][column] != 0)
{
end = false;
return max;
}
}
while(end)
the code hasn’t tested yet so it may contains bug and error, but this is not the main point anyway.
I would like to find out the cost of this method, but I have no idea how to calculate it.
The cost I want is Running time T(n) and Big-Oh notation. If possible, the method should running in O(n) time ( not O(n^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
endfalse whenrowandcolumnequal the size of your matrix.