二分插入排序思路
先在有序区通过二分查找的方法找到移动元素的起始位置,然后通过这个起始位置将后面所有的元素后移。
二分插入排序实现
Function.prototype.method = function(name, func){ this.prototype[name] = func; return this; }; Array.method('bInsertSort', function(){ var len = this.length, i, j, tmp, low, high, mid; for(i=1; i<len; i++){ tmp = this[i]; low = 0; high = i - 1; while(low <= high){ mid = (low+high)/2; if(tmp < this[mid]) high = mid - 1; else low = mid + 1; } for(j=i-1; j>=high+1; j--){ this[j+1] = this[j]; } this[j+1] = tmp; } return this; });