Java rarrange enum array

后端 未结 2 810
無奈伤痛
無奈伤痛 2021-01-22 18:11

i was wondering how can i reorder enum so that all goats are at the beginning and all sheep are at the end of the array. Right now it actually does the trick but until the arra

2条回答
  •  野性不改
    2021-01-22 18:31

    If you want to have maximum performance for such a special case you may simply count the number of one of the two possible values and overwrite the array accordingly to get the result that sorting would create:

    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);
    

    }

    You can see it as a modified version of counting sort.

提交回复
热议问题