pretty newbie question I think but I've spent over 6 hours doing this one way and another and I don't know whats the best way doing it, so I am asking for your help about how it is suppost to be done.
I have 2 enums, for example car and bike. I have to make list
or array
(I don't know which is better) that has 2 - 1 000 000 elements inside and when it's done I have to reorder the list
/array
(bikes at the beginning and cars in the end). There are only a bike and a car, but there can be hundreds or thoulsands or even more of them. I don't know if it's possible to make EnumMap
about 2 enums.
EnumMap
has key and value, so I gave key "car" and value "0", and key "bike" value "1", so it would be easier to reorder, but I found out I can't do this on EnumMap
, because does't matter how much elements I add, there is always only 2, bike and car. Can't talk about hundreds there I assume.
The reason why I haven't focused on array, is in the beginning of code there is enum garage {bike, car};
This is homework yes, but I just hope to find out the method for doing it (spent hours just reading and trying different approaches), not that someone does it for me.
I suggest you split the logic into two methods, first countGoats(Animal[])
-
private static int countGoats(Animal[] animals) {
int count = 0;
for (Animal a : animals) {
if (Animal.goat == a) {
count++;
}
}
return count;
}
Since every element up to the goats
count should be a goat
in the array (and every element after a sheep
) we can then iterate the array with something like,
public static void reorder(Animal[] animals) {
if (animals == null) {
return;
}
int goats = countGoats(animals);
for (int i = 0; i < animals.length; i++) {
// if (i < goats) - it's a goat, otherwise it's a sheep.
animals[i] = (i < goats) ? Animal.goat : Animal.sheep;
}
}
This is an example of a Counting sort and has a run-time complexity of O(n). As the Wikipedia article notes,
Because counting sort uses key values as indexes into an array, it is not a comparison sort, and the Ω(n log n) lower bound for comparison sorting does not apply to it.