I am inserting items from a class I've created into a linked list, but I must find the correct index point to insert them to (so the items are in alphabetical order) before I add it.
I have some working code but it's ridiculously inefficient, taking 5 ish minutes on a semi-decent machine to add 10000 items. I was wondering if there is a more efficient way of doing this.
As of now, the only way I have managed to get it to work is as so. Any other methods end up adding items incorrectly (I'm guessing not correctly adding to the end of a list)
In the code shown, I am passing in a name (along with two other variables, that are irrelevant and already part of the itemClass) into the following code
if (llist.size() == 0) {
llist.add(itemClass);
}
else if (llist.get(0).name.compareTo(name)>0) {
llist.add(0, itemClass);
}
else if (llist.get(llist.size() - 1).name.compareTo(name) < 0) {
llist.add(llist.size(), itemClass);
}
else {
int i = 0;
while (llist.get(i).name.compareTo(name) < 0) {
i++;
}
llist.add(i, itemClass);
}
This currently works, exactly as intended, but as said, takes incredibly long. I was just expecting something quicker, by possibly a large margin.