Use javascript to sort the ints array by the distance the element is from a given target

Algorithm: distanceSort (array, target)
Input: array from int sorted from smallest to largest and int to measure distance from
Output: array sorted by distance from target


The
distanceSort example ([- 10, -6,3,5], 1)
returns [3, 5, -6, -10]

+4
source share
3 answers

Here is a way to do it. Using Array.sortfunction

var a = [-10, -6, 3, 5, 99, 76, -100];

function distanceSort(arr, target) {
   return arr.sort(function(a, b) {
      var distance1 = Math.abs(target - a);
      var distance2 = Math.abs(target - b);

      return distance1 == distance2 ? 0 : (distance1 > distance2 ? 1 : -1);
   });
}

console.log(distanceSort(a, 100)); //[99,76,5,3,-6, -10, -100]
console.log(distance(a, -5)); //[-6, -10, 3, 5, 76, -100, 99]
+3
source

( ), ( ).

, 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));   //[3, 5, -6, -10]
console.log(distanceSort([-10,-6,3,5], -11)); //[-10, -6, 3, 5]
console.log(distanceSort([-10,-6,3,5], -10)); //[-10, -6, 3, 5]
console.log(distanceSort([-10,-6,3,5], 5));   //[5, 3, -6, -10]
console.log(distanceSort([-10,-6,3,5], 6));   //[5, 3, -6, -10]
+2
var distanceSort = function distanceSort(nArr, x){
    return nArr.sort(function(n1, n2){
        return Math.abs(n1 - x) - Math.abs(n2 - x);
    });
}

console.log(distanceSort([-10,-6, 57, 54, 11, -34, 203, -140, 3, 5], 1));
//--> [3, 5, -6, 11, -10, -34, 54, 57, -140, 203]

This translates well to ECMA6 (if you are using Babel):

var distanceSort = (nArr, x) => 
    (nArr.sort((n1, n2) =>
        (Math.abs(n1 - x) - Math.abs(n2 - x))));
+1
source

Source: https://habr.com/ru/post/1609878/


All Articles