Java rarrange枚举数组

我想知道如何重新排序枚举,以便所有山羊都在开始,所有的绵羊都在arrays的末尾。 现在它实际上是诀窍,但直到数组大小> 100 ..重新排序速度也很重要所以api方法有点太慢。 有什么建议么?

public class Sheep { enum Animal {sheep, goat}; public static void main (String[] param) { reorder(Animal.values()); } public static void reorder (Animal[] animals) { int l, r, i, j; i = l = 0; //left most element r = animals.length - 1;//right most element int mid = (r+l)/2; // middle element of the array for(i=0; i < animals.length;i++) { if(i = mid ) { animals[i] = animals[r-1]; System.out.println(animals[r]); } } } } 

由于enum实现了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在评论中建议的方法是最好的:只计算有多少只绵羊和山羊并打印相应的值很多次

如果您希望在这种特殊情况下获得最大性能,您可以简单地计算两个可能值中的一个的数量并相应地覆盖该数组以获得排序将创建的结果:

 public static void reorder (Animal[] animals) { assert Animal.values().length==2; int numGoat=0; for(Animal a:animals) if(a==Animal.goat) numGoat++; Arrays.fill(animals, 0, numGoat, Animal.goat); Arrays.fill(animals, numGoat, animals.length, Animal.sheep); 

}

您可以将其视为计数排序的修改版本。