java enum 数组_Java Rarrange枚举数组

由于枚举实现了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在注释中建议的方法是最好的:只计算有多少只绵羊和山羊,然后打印相应的值很多次.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值