i know insertion sort isn’t that great…but even still…what are two more simple improvements that could be made to the sort below?
public static void insertion_sort_with_moves(int[] arr){
for (int i = 1; i <= arr.length; i++){
int v = arr[i-1];
int j = i-1;
for (/*declared j outside loop*/; j > 0; j--) {
//compswap(a[j-1], a[j]);
if (v < arr[j-1]) arr[j] = arr[j-1];
else break;
}
arr[j] = v;
}
}
A few micro-optimizations are:
1,2,3)
Saves you from computing i-1 two times and ++i is faster than i++.
Not sure about the length thing (could save the offset addition when accessing a class member).
4,5)
j!=0 should be faster than j>0 (really don’t expect much) and –j is faster than j–.
Well most of them may be platform dependent and may make no difference at all.