I read “Introduction to Algorithms” by Cormen&Co and implement algorithm on java. I wonder does it make sense to write into insertion sort code if-statement at the final set() method? I want make code more faster if it is possible.
public static void insertion(List<Integer> a) {
List<Integer> aList = a;
int temp;
int previousIndex;
for (int i = 1; i < aList.size(); i++) {
temp = aList.get(i);
previousIndex = i - 1;
while ((previousIndex >= 0) && aList.get(previousIndex) > temp) {
aList.set(previousIndex + 1, a.get(previousIndex));
previousIndex--;
}
//if(aList.get(previousIndex + 1) > temp){
aList.set(previousIndex + 1, temp);
//}
}
}
Excuse me, if it is elementary. I am very beginner.
This looks like an attempt to optimize the code, making it faster. The apparent idea is to make a test on the data to avoid setting it. This would make execution faster only if (1) reading and testing the value is faster than setting the value and (2) there is enough cases when the test will avoid setting the value.
IMO (1) is dubious and (2) would need to be very often to be save much time, and I do not think that is the case.
A better faster test could be achieved by testing (previousIndex + 1 != i) instead of (aList.get(previousIndex + 1) > temp), and that may be a good optimization if the copying of objects of the list would be much more time consuming, like copying complex object structures. However, in out case, we are talking about Integer objects, so my take is that adding the test will only slow down things in all cases.
Of course, as it is the case with all optimizations, only real life measurements will tell what is effective, and that is why optimization is always the last thing to do, and only when necessary.