I have a list of lists which need to be sorted based on the length of the lists. What I am doing now is first inserting the lists into the main list and then sort the main list giving key=len
. This steps will take a total time of n + nlg(n)
. Is it possible to maintain a sorted list while entering the data into the main list? Can it be done using bisect (or is there any better way) and if so will it perform better thann + nlg(n)
?
Asked
Active
Viewed 70 times
1
-
3try [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/sortedlistwithkey.html) – syntonym Aug 24 '16 at 21:11
-
This [`SortedCollection`](http://code.activestate.com/recipes/577197-sortedcollection/) reciple may be helpful (which uses `bisect`). – martineau Aug 24 '16 at 22:21
1 Answers
1
It depends on the data structure you are using:
- Dynamic Array
- Finding the right index on a sorted array is
O(log n)
using a bisect - Inserting is
O(n)
as you have to shift everything - Total `O(n)
- Finding the right index on a sorted array is
- Linked List
- Finding the right index on a sorted linked list requires browsing the list until you get there. (
O(n)
) - Inserting is a simple operation, takes only
O(1)
. - Total
O(n)
- Finding the right index on a sorted linked list requires browsing the list until you get there. (
- Self-balancing BST
- Inserting while maintaining the order and the balance is
O(log n)
amortized - There are links to implementations in this question
- Inserting while maintaining the order and the balance is
- Heap. Not exactly what you ask, but inserting into a heap is
O(log n)
orTheta(1)
depending on the implementation you use. heapq in python is one implementation. You simple push items in your heap, and when you are done, you can get the sorted result inO(n)
. Meanwhile you can access the root of the tree inO(1)
, and the k smallest, sorted, inO(k)
.

njzk2
- 38,969
- 7
- 69
- 107