-2

What is the time & complexity of the code below?

function SortFunction (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

I thought the time complexisty could be O(n^2) but there are different answers on the internet for similar situations, so I was confused. And what about the space complexity?

And an extra small question about this topic:

function PrintCol():
    colours = { "Red", "Green", "Blue", "Grey" }
    foreach colour in colours: 
        print(colour)

The time complexity here is O(n) since there is only one loop, right? Space complexity?

Sneftel
  • 40,271
  • 12
  • 71
  • 104
noob123
  • 59
  • 1
  • 6
  • 3
    please ***don't tag*** irrelevant languages to get more attention, _thank you very much_ (also: those "different answers" and their explanations might be interesting) – Franz Gleichmann May 03 '22 at 14:07
  • You outer loop runs n times. Your inner loop starts with n but will be smaller by one every run of the outer loop. This should help you calculate big O. – Simon Kraemer May 03 '22 at 14:09
  • You need to know the complexity of enumerating and the `add()` and `remove()` functions. They depend on the data structure that you are using. The space complexity also depends on that data structure. – Jakob Stark May 03 '22 at 14:12

1 Answers1

0

There are n iterations of the outer while loop, and the cost of each iteration is O(n). This is assuming that the add and remove methods each run in linear time. The total cost is then O(n^2).

Your second program would have cost O(n).

Ashwin Ganesan
  • 331
  • 1
  • 4