Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster to sort a list after inserting items or adding them to a sorted list

If I have a sorted list (say quicksort to sort), if I have a lot of values to add, is it better to suspend sorting, and add them to the end, then sort, or use binary chop to place the items correctly while adding them. Does it make a difference if the items are random, or already more or less in order?

like image 603
Steve Avatar asked Oct 03 '08 21:10

Steve


People also ask

Is it faster to insert sorted or sort after?

Either way, inserting into a sorted list (or something like a Binary Search Tree) should be faster.

What is the most efficient way to sort a list?

Quicksort. Quicksort is one of the most efficient sorting algorithms, and this makes of it one of the most used as well. The first thing to do is to select a pivot number, this number will separate the data, on its left are the numbers smaller than it and the greater numbers on the right.

Is insertion sort faster?

Insertion sort is faster than some of the other O(n^2) sort algorithms because it has less overhead (especially when compared with bubble sort). There are also variations of sorting algorithms.

Is quick sort or insertion sort faster?

Insertion sort is faster for small n because Quick Sort has extra overhead from the recursive function calls. Insertion sort is also more stable than Quick sort and requires less memory.


2 Answers

Usually it's far better to use a heap. in short, it splits the cost of maintaining order between the pusher and the picker. Both operations are O(log n), instead of O(n log n), like most other solutions.

like image 43
Javier Avatar answered Sep 21 '22 19:09

Javier


If you add enough items that you're effectively building the list from scratch, you should be able to get better performance by sorting the list afterwards.

If items are mostly in order, you can tweak both incremental update and regular sorting to take advantage of that, but frankly, it usually isn't worth the trouble. (You also need to be careful of things like making sure some unexpected ordering can't make your algorithm take much longer, q.v. naive quicksort)

Both incremental update and regular list sort are O(N log N) but you can get a better constant factor sorting everything afterward (I'm assuming here that you've got some auxiliary datastructure so your incremental update can access list items faster than O(N)...). Generally speaking, sorting all at once has a lot more design freedom than maintaining the ordering incrementally, since incremental update has to maintain a complete order at all times, but an all-at-once bulk sort does not.

If nothing else, remember that there are lots of highly-optimized bulk sorts available.

like image 130
comingstorm Avatar answered Sep 18 '22 19:09

comingstorm