Java tutorial
//package com.java2s; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Main { /** * 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. */ 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; } /** * Returns a comparator based on whether the order is ascending or not. * Has a dummy parameter to make sure generics can infer the type correctly. */ static <T extends Comparable<T>> Comparator<T> getComparator(boolean ascending, T dummy) { Comparator<T> comp; if (ascending) { comp = new Comparator<T>() { public int compare(T o1, T o2) { return o1.compareTo(o2); } }; } else { comp = new Comparator<T>() { public int compare(T o1, T o2) { return o2.compareTo(o1); } }; } return comp; } }