( ), ( ).
, oposing, .
- O (log n), - O (n). O (n).
function lowerBound(arr, target) {
var first = 0,
count = arr.length;
while (count > 0) {
var step = count / 2;
var it = first + step;
if (arr[it] < target) {
first = it + 1;
count -= step + 1;
} else {
count = step;
}
}
return first;
}
function distanceSort(arr, target) {
var answer = [];
var j = lowerBound(arr, target);
var i = j-1;
while (i >= 0 || j<arr.length) {
if (j >= arr.length || target-arr[i]<arr[j]-target)
answer.push(arr[i--]);
else
answer.push(arr[j++]);
}
return answer;
}
console.log(distanceSort([-10,-6,3,5], 1));
console.log(distanceSort([-10,-6,3,5], -11));
console.log(distanceSort([-10,-6,3,5], -10));
console.log(distanceSort([-10,-6,3,5], 5));
console.log(distanceSort([-10,-6,3,5], 6));