'Time and space complexity - for loop inside of while loop
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?
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ashwin Ganesan |