java - insertion sort...tweaks to improve? -
i know insertion sort isn't great...but still...what 2 more simple improvements made sort below?
public static void insertion_sort_with_moves(int[] arr){ (int = 1; <= arr.length; i++){ int v = arr[i-1]; int j = i-1; (/*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)
int len = arr.length; ... (int = 0; < len; ++i){ int v = arr[i]; int j = i;
saves computing i-1 2 times , ++i faster i++. not sure length thing (could save offset addition when accessing class member).
4,5)
for (/*declared j outside loop*/; j != 0; --j) {
j!=0 should faster j>0 (really don't expect much) , --j faster j--.
well of them may platform dependent , may make no difference @ all.
Comments
Post a Comment