static <T extends Comparable<T>> ArrayList<T> sortedMerge(List<T> a1, List<T> a2,
      boolean ascending, int n) {

    Comparator<T> comparator = getComparator(ascending, (T)null);
    
    int n1 = a1.size();
    int n2 = a2.size();
    int p1 = 0; // The current element in a1
    int p2 = 0; // The current element in a2
    
    ArrayList<T> output = new ArrayList<T>(n); 
    
    while (output.size() < n && (p1 < n1 || p2 < n2)) {
      if (p1 < n1) {
        if (p2 == n2 || comparator.compare(a1.get(p1), a2.get(p2)) < 0) {
          output.add(a1.get(p1++));
        }
      }
      if (output.size() == n) {
        break;
      }
      if (p2 < n2) {
        if (p1 == n1 || comparator.compare(a2.get(p2), a1.get(p1)) <= 0) {
          output.add(a2.get(p2++));
        }
      }
    }

    return output;
  }
Merge two ascending/descending array and keep the first n elements.
@param ascending
           if true, the array is sorted in ascending order,
           otherwise it is in descending order.
contrib/src/java/org/apache/hadoop/hive/contrib/udaf/example/UDAFExampleMaxMinNUtil.java