Generally, what is better: insert N elements in some collection and then sort it, or find out the correct place for the element before insert and insert it exactly in that place (repeat N times)?
Generally, what is better: insert N elements in some collection and then sort it,
Share
It is very dependent on the data structure and application in use.
Note that inserting an element in an array requires shifting all the following elements to the right, which results in
O(n)insertion.A Binary Search Tree however, allows insertion in
O(logn), but is less cache efficient then an array – and thus slower.On the other hand, inserting and then sorting results in high latency after the last element was inserted [The
O(nlogn)sort].Also – if you are going to query very often – but add elements seldom – you want to avoid sorting too often – and keeping elements in order is an easy way to achieve this.