开发者

insertion sort...tweaks to improve?

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 insertio开发者_开发问答n_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;
    }
}


One thing that comes to mind is that you could use a binary search on the sorted part of array to find where it belongs and use System.arraycopy to move the subarray over by one more efficiently than iterating through. You're still O(n^2) but on large arrays it will be a small improvement.

Another is to declare any variables that won't change as final to allow for compiler optimization (as I noted in my comment.)


A few micro-optimizations are:

1,2,3)

    int len = arr.length; 
...

    for (int i = 0; i < len; ++i){
            int v = arr[i];
            int j = i;

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)

for (/*declared j outside loop*/; j != 0; --j) {

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.


Updated based on comments:

Some improvements to help readability:

  1. Don't use underscores in your method names. Use camel case instead.
  2. Consider curly braces around if/else statements to make them easier to read or at least put in more new lines.
  3. Remove code that is commented it out if it is not needed.
  4. Consider removing comments that explain "what" instead of "why".
  5. Try to avoid one character variables especially when you have several in the same scope.
  6. You might be able to make use of a for each loop rather than having to declare and access the v variable. (Would still need the current index, but other changes might allow this)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜