Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O runtime efficiency doubts

Is O(n) considered as faster compared to O(n log n)? If I have a function that does a loop, which is O(n) then a merge sort outside the loop O(n log n) then the run time would be O(n log n) I assume?

like image 665
xonegirlz Avatar asked Mar 21 '26 14:03

xonegirlz


1 Answers

Is O(n) considered as faster compared to O(n log n)?

No, not directly. Big-O notation is about the limiting factor in an algorithm, which has more to do with an algorithms scalability than speed. You can have a routine that's O(1) which takes longer than a routine of O(n^2) for a specific set of data - but the former will scale much better.

That being said, in general, O(n) will of course scale better than O(n log n), and would likely be considered "faster" or "better".

If I have a function that does a loop, which is O(n) the a O(n log n) then the run time would be O(n log n) I assume?

It's unclear exactly what you're saying here -

If you mean you have a loop with 2 functions, ie:

Loop over N elements
    - Call O(n) function
    - Call O(n log n) function

Then the overall limiting factor is going to be O(n^2 log n).

(From Comment)

I mean the merge sort (n log n) is outside the loop, so still it would be O(n log n)

If, instead, you're saying you're going to do something like:

- Call O(n log n) function
- Loop over N elements
     - Process each element using O(1) algorithm

Then the overall complexity is still O(n log n), as that is the limiting factor. This is because "O(n + n)" is still O(n).

like image 164
Reed Copsey Avatar answered Mar 24 '26 11:03

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!