I have been programming in PHP for a long time now, and as I don’t come from a computer science / math background I only have a basic understanding of the Big O notation, so I have taken a function and tried to improve it and express them both in Big O:
Example 1
function foo($j) {
$ids = array();
while (count($ids) < $j) {
$id = gen_id(); // assume this function will return you an integer
if (!in_array($id, $ids)) {
$ids[] = $id;
}
}
return $ids;
}
I would improve this function by removing the while loop for count($ids) and replace with forloop So that count($ids) doesn’t have to be evaluated every time in the loop, and also replace is_array with isset and move the values to keys (isset is quicker than in_array)
Example 2 – Improved
function foo($j) {
$ids = array();
for($i = 1; $i<= $j; ++$j) {
$id = gen_id(); // assume this function will return you an integer
if (!isset($ids[$id])) {
$ids[$id] = true;
}
else {
--$i;
}
}
return $ids;
}
I would express the above functions with the following Big O Notation:
Example 1: O(n^2), Example 2: O(n)
Am I correct with my notations? Is there a better way still to do the same function?
Thanks in advance!
Here is how I would write that function in a more straightforward approach: The inner
forloop is the perfect scenario for ado ... whileloop.Edit: Actually, this function is
O($j)/O(n), sincegen_id()andisset()are both constantO(1)(isset()is a hash table lookup). So, the inner efficiency of theforloop is constant timeO(1), making the whole functionO(n).