js 二分查找
程序员文章站
2022-05-07 11:38:55
...
仿Java collections里的实现
var binarySearch = function(items, value, comp){ var low = 0, high = items.length - 1, mid, tmpC; comp = comp || function(v, item) { return v < item ? -1 : (v > item ? 1 : 0); }; while(low <= high && (tmpC = comp(value, items[mid = (high + low) >>> 1])) != 0){ if (tmpC < 0){ high = mid - 1; } else { low = mid + 1; } } return tmpC == 0 ? mid : (-low - 1); }
数值数组排序
numArr.sort(function(a,b) { return a - b });
有序数组去重
var uniqueOrderedArray = function (arr){ var rs = [], preE, aLen = arr.length; if (aLen > 0) { preE = arr[0]; rs.push(preE); } for(var i = 1; i < aLen; i++){ if(arr[i] !== preE){ preE = arr[i]; rs.push(preE); } } return rs; }