Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 19th, 2010 | Syntax: Java 5 | Size: 1.36 KB | Hits: 51 | Expires: Never
Copy text to clipboard
  1.         public static class TopNExtractor {
  2.                 private static class ReverseOrderComparator<G extends Comparable<? super G>> implements Comparator<G> {
  3.                         @Override
  4.                         public int compare(G o1, G o2) {
  5.                                 return -(o1.compareTo(o2));
  6.                         }      
  7.                 }
  8.                 public static <G extends Comparable<? super G>> List<G> extract(List<G> source, int n) {
  9.                         List<G> result = extractWithoutSort(source, n);
  10.                         // how can i sort as reverse order
  11.                         Collections.sort(result, new ReverseOrderComparator<G>());
  12.                         Collections.reverse(result);
  13.                         return result;
  14.                 }
  15.                 public static <G extends Comparable<? super G>> List<G> extractWithoutSort(List<G> source, int n) {
  16.                         if (source.size() == 0)
  17.                                 return null;
  18.                         G pivot = source.get(0);
  19.                         int sourceSize = source.size();
  20.                         List<G> below = new ArrayList<G>(sourceSize / 2), above = new ArrayList<G>(sourceSize / 2);
  21.                         List<G> equal = new ArrayList<G>();
  22.                         for (G s : source) {
  23.                                 if (s.compareTo(pivot) < 0)
  24.                                         below.add(s);
  25.                                 else if (s.compareTo(pivot) > 0)
  26.                                         above.add(s);
  27.                                 else
  28.                                         equal.add(s);
  29.                         }
  30.                         if (above.size() > n)
  31.                                 return extractWithoutSort(above, n);
  32.                         else if (above.size() + equal.size() > n) {
  33.                                 above.addAll(equal.subList(0, n - above.size()));
  34.                                 return above;
  35.                         } else {
  36.                                 above.addAll(equal);
  37.                                 above.addAll(extractWithoutSort(below, n - above.size()));
  38.                                 return above;
  39.                         }
  40.                 }
  41.         }