小编典典

Java Rarrange枚举数组

java

我想知道如何重新排序枚举,以便所有山羊都在数组的开头而所有羊都在数组的结尾。现在,它实际上可以解决问题,但是要等到数组大小>
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[l+1];

                System.out.println(animals[r]);

            } else if(i >= mid )
            {   
                animals[i] = animals[r-1];
                System.out.println(animals[r]);

            }

        }

   }
}

阅读 250

收藏
2020-11-26

共1个答案

小编典典

由于是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) {
        /*
         * 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在注释中建议的方法是最好的:只需计算有多少只绵羊和山羊,然后打印相应的值即可很多次。

2020-11-26