由于是
enumImplements
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<Animal> 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) { while (animals[first].ordinal() == 1 && first < last) { ++first; } while (animals[last].ordinal() == 0 && first < last) { --last; } if (first < last) { Animal temp = animals[first]; animals[first] = animals[last]; animals[last] = temp; ++first; --last; } }}但是,如果您需要做的只是生成正确的输出(而不是对数组进行实际排序),那么@ajb在注释中建议的方法是最好的:只需计算有多少只绵羊和山羊,然后打印相应的值即可很多次。



