Get the N smallest [comparable] items in a set

I have an unsorted collection of objects [comparable], is it possible to get a list from a list of a list without the need for sorting?

I was considering making a SortedList with a limited ability, but that doesn't seem like the right option.

I could easily write this, but I was wondering if there is another way.

I cannot modify the existing collection structure.

+5
source share
4 answers

sort(), , O (n log (n)). O (n) - .

Guava ( Java- Google); Ordering :

quickselect, , Set k . Guava, docs , , .

, , TreeSet, /, O (1) hash-based Set, O (n log (n)). , . O (n log (n)), fancier heap. GraphMaker, .

, , , .

+5

, , . N . :

  • , .
+1

, max heap data N, , ( get() "" ). , . O(M)+lg(N) O(M) ( M - ) , . :

MaxHeap maxHeap = new MaxHeap(N);
for (Item x : mySetOfItems) {
  if (x < maxHeap.get()) {
    maxHeap.add(x);
  }
}

The Apache Commons Collections PriorityBuffer class seems to be their flagship heap binary data structure, try this one.

+1
source
0
source

All Articles