I want to write a list-lie class in python, that automatically sorts itself when numbers are added. This is for fun, not for a class :p What I’m wondering is what’s the most efficient way to go about doing this. Should I just do something like this? :
class SortedList:
def __init__(self, data):
self.data = list(data)
def add(self, num):
self.data.append(num)
self.data.sort()
Is there a better way of doing this?
-Edit-
sort()is O(n log n). Adding n numbers to the list by sorting after each number added will be O(n^2 log n) (but in practice this may turn out to be faster than O(n^2) algorithms, depending on the optimization of the sort).A better O implementation is taking O(n) time to search for the insertion position and O(n) time to add a new number to the list (total time still O(n)). Adding n numbers to the list will be O(n^2). Code follows:
We can do better by binary searching our way to the right index in O(log n) time. Adding a new number to a list is O(n). Since this entire operation is (a better than before) O(n), adding n numbers to the list is O(n^2) with a lower constant. (Code not included)
If you were to add new numbers in large groups, however, it will speed up the algorithm considerably if you add them all at once (use
extend()) and then sort. Then, adding n numbers will be done in O(n log n) time (same time as sorting).See http://wiki.python.org/moin/TimeComplexity