My answer is O(D + R). Is it correct?
I want to figure out the Big-O of this code. I am doing an independent coursework on data structures and algorithms.
This code is lifted from the book "Data Structure and Algorithms in JavaScript" by Ms. L Groiner, PacktPub, which I am studying right now.
Please see below:
function baseConverter(decNumber, base) {
var remStack = new Stack(), //instantiate class, define variable, O(1)
rem, // define var, O(1)
baseString = '', //initialize, O(1)
digits = '0123456789ABCDEF'; //initialize, O(1)
while(decNumber>0) { //loop, D times:
rem = Math.floor(decNumber % base); //modulo/Math/assignment, O(1)
remStack.push(rem); //push to stack, O(1)
decNumber = Math.floor(decNumber / base); //divide, Math, assignment, O(1)
}
while(!remStack.isEmpty()){ //loop, R times:
baseString += digits[remStack.pop()]; //pop/index/Math/addition assignment, O(1)
}
return baseString; // O(1)
}
I simplify each operation, line-by-line, like so:
4 * O(1) + D * 3 * O(1) + R * O(1) =
3 * O(D) + 1 * O(R) =
O(D) + O(R) = O(D + R)
I have gone over my own web development notes and looked at various books. But I can only form snippets and deduce from it. I would like to find a standardized framework or at least build it in my mind to be able to state the run time in Big-O correctly. Giving me feedback on this, helps me to do so.