由于枚举实现了Comparable,因此您可以简单地对数组进行排序然后反转:
public static void reorder(Animal[] animals) {
Arrays.sort(animals);
for (int i = 0, j = animals.length - 1; i < j; ++i, --j) {
Animal tmp = animals[i];
animals[i] = animals[j];
animals[j] = tmp;
}
}
您也许还可以做到以下几点:
List list = Arrays.asList(animals);
Collections.sort(list);
Collections.reverse(list);
这与API调用基本相同,只是将数组包装在List对象中的开销非常小.您甚至可以这样做:
Arrays.sort(animals, Collections.reverseOrder());
(感谢Bhesh Gurung提出的建议.)
编辑:如果您必须正好处理两个值,则可以通过简单地从两端进行扫描来进行更好的处理,因为当您发现两个元素乱序时进行交换:
public static void reorder(Animal[] animals) {
int first = 0;
int last = animals.length - 1;
while (first < last) {
/*
* The unsorted elements are in positions first..last (inclusive).
* Everything before first is the higher animal; everything after
* last is the lower animal.
*/
while (animals[first].ordinal() == 1 && first < last) {
++first;
}
while (animals[last].ordinal() == 0 && first < last) {
--last;
}
if (first < last) {
/*
* At this point, the sort conditions still hold and also we know
* that the animals at first and last are both out of order
*/
Animal temp = animals[first];
animals[first] = animals[last];
animals[last] = temp;
++first;
--last;
}
}
}
但是,如果您需要做的只是生成正确的输出(而不是对数组进行实际排序),那么@ajb在注释中建议的方法是最好的:只计算有多少只绵羊和山羊,然后打印相应的值很多次.