0

I am struggling to wrap my head around Big O notation and saw the following problem online. I must answer determining whether the following code is O(n), O(n²), O(logn), O(nlogn)

I have watched several videos but am still failing to understand Big O. Can someone please advise to the answer and their methodology for getting there?

function sortSmallestToLargest(entries):
    sorted_entries = {};

    while entries is not empty:
        smallest_entry = entries[0]

        foreach entry in entries:
            if (entry < smallest_entry):
                smallest_entry = entry

        sorted_entries.add(smallest_entry)
        entries.remove(smallest_entry)

    return sorted_entries
3
  • Maybe try my answer here: stackoverflow.com/questions/64370621/… Commented Nov 28, 2020 at 23:26
  • Could you fix the identation? is sorted_entries.add(smallest_entry) inside the for loop, or perhaps the if? We can't tell. Commented Nov 28, 2020 at 23:28
  • 1
    I've submitted an edit according to how I think it should look - in which case the complexity is O(n^2) Commented Nov 28, 2020 at 23:31

1 Answer 1

2

The algorithm iterates multiple time on 'entries' until it gets empty. first time in the inner loop it iterates n time (assuming entries length is n at start). second time in the inner loop it iterates n-1 time (because one item was removed in the previous iteration). So at the end we have this series of iterations:

n + (n-1) + (n-2) + ... + 1 = n(n+1)/2 = O(n^2)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.