在某些情况下,仅仅为了进行排序而创建新类没有多大意义。
这里,是一个函数,可用于根据键列表()对任意数量的任意类型列表()进行排序。这里就是一个例子。List<?>
List<T implements Comparable>
用法
下面是如何使用该函数对任意类型的多个列表进行排序的示例:
List<Integer> ids = Arrays.asList(0, 1, 2, 3);
List<String> colors = Arrays.asList("blue", "yellow", "red", "black");
List<String> clothes = Arrays.asList("shoes", "pants", "boots", "coat");
// Sort By ID
concurrentSort(ids, ids, colors, clothes);
// Sort By Color
concurrentSort(colors, ids, colors, clothes);
// Sort By Clothes
concurrentSort(clothes, ids, colors, clothes);
输出:
// Sorted By ID:
ID: [0, 1, 2, 3]
Colors: [blue, yellow, red, black]
Clothes: [shoes, pants, boots, coat]
// Sorted By Color:
ID: [3, 0, 2, 1]
Colors: [black, blue, red, yellow]
Clothes: [coat, shoes, boots, pants]
// Sorted By Clothes:
ID: [2, 3, 1, 0]
Colors: [red, black, yellow, blue]
Clothes: [boots, coat, pants, shoes]
法典
可以在这里找到一个Ideone示例,其中包括参数验证和测试用例。
public static <T extends Comparable<T>> void concurrentSort(
final List<T> key, List<?>... lists){
// Create a List of indices
List<Integer> indices = new ArrayList<Integer>();
for(int i = 0; i < key.size(); i++)
indices.add(i);
// Sort the indices list based on the key
Collections.sort(indices, new Comparator<Integer>(){
@Override public int compare(Integer i, Integer j) {
return key.get(i).compareTo(key.get(j));
}
});
// Create a mapping that allows sorting of the List by N swaps.
// Only swaps can be used since we do not know the type of the lists
Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
List<Integer> swapFrom = new ArrayList<Integer>(indices.size()),
swapTo = new ArrayList<Integer>(indices.size());
for(int i = 0; i < key.size(); i++){
int k = indices.get(i);
while(i != k && swapMap.containsKey(k))
k = swapMap.get(k);
swapFrom.add(i);
swapTo.add(k);
swapMap.put(i, k);
}
// use the swap order to sort each list by swapping elements
for(List<?> list : lists)
for(int i = 0; i < list.size(); i++)
Collections.swap(list, swapFrom.get(i), swapTo.get(i));
}
注意:运行时间是列表的长度,并且是列表的数量。通常这样运行时间并不比只排序键更重要。O(mlog(m) + mN)
m
N
m >> N
O(mlog(m))