You want to be careful here. You decided to use an algorithm that gradually creates a sorted data structure so that (I accept) you can display a progress bar. However, you may have chosen a sorting method that is significantly slower than optimal. (Both types will be O(NlogN) , but there is more performance than Big-O behavior ...)
If you are concerned that this might be a problem, compare the sorting time of a typical collection using TreeMap and Collections.sort . The latter works by copying the input collection into an array, sorting the array and copying it back. (It works best if the input collection is an ArrayList. If you do not need the result as a modified collection, you can avoid the final copy using Collection.toArray , Arrays.sort and Arrays.asList .)
An alternative idea would be to use a Comparator object that tracks the number of times it has been called, and use it to track the progress of the sort. You can use the fact that the comparator is usually called about N*log(N) times, although you may need to calibrate it against the actual algorithm used 1 .
By the way, counting calls to the comparator will give you a better idea of โโthe progress that you will get by counting the inserts. As you approach the end of the sort, the deceleration rate slows down.
(You will have different threads reading and writing the counter, so you need to consider synchronization. Declaring the counter as volatile will work due to additional memory traffic. You can also just ignore the problem if you are happy that the progress bar sometimes shows outdated values. .. depending on your platform, etc.)
1 - The problem with this. There are some algorithms in which the number of comparisons can vary greatly depending on the initial data sorting order. For such an algorithm, it is impossible to calibrate the counter, which will work in "not average" cases.
Stephen c
source share