0

What will be a complexity of min heap in my case?

I need to figure out 5 smallest numbers in a list.

What I do is

public List<Integer> mins(final List<Integer> list) {
        final PriorityQueue<Integer> mins = new PriorityQueue<>(5, Comparator.reverseOrder());
        for (final int num: list) {
            if (mins.size() > 4) {
                if (mins.peek() > num) {
                    mins.poll();
                    mins.add(num);
                }
            } else {
                mins.add(num);
            }
        }
        final List<Integer> result = new ArrayList<>(mins);
        Collections.sort(result);
        return result;
}

Is it correct that the complexity of the piece of code is O(nlog5) -> O(n)? In many sources, I see that the complexity of Min Heap is nlog(n). Is it correct of the complexity of Min Heap is nlog(m) where m is a size of a heap?

Pasha
  • 1,768
  • 6
  • 22
  • 43
  • A data structure doesnt have a complexity of its own, but operations on it do. In this case you are bth inserting into and removing from a heap. – user207421 Mar 15 '19 at 00:39
  • To compound on what @user207421 mentions, there's different implemenations of heaps that have different time complexities for deletion / insertion as well. see [the wikipedia page](https://en.wikipedia.org/wiki/Heap_(data_structure)#Comparison_of_theoretic_bounds_for_variants) for a few. – Dillon Davis Mar 15 '19 at 00:59
  • In your case, since the size is constant, operations on the heap would be constant. – Dillon Davis Mar 15 '19 at 01:00
  • 1
    No, but *log(M)* is, for one poll, assuming a binary heap. – user207421 Mar 15 '19 at 01:20
  • And Nlog(M) for add() N times in queue of size M? If on each add() when size > M I poll() the an item? – Pasha Mar 15 '19 at 01:35

0 Answers0