如何使用选择排序功能从小到大对IP地址进行排序?

问题描述 投票:0回答:1
const selectionSort = (arr) => {

     for ( i = 0; i < arr.lenght; i++) {

        for (j = i + 1; j < arr.length; j++) {

          let lastIpPartOfIndex= arr[i].target.toString().split('.')[arr[i].target.toString().split('.').length -1]
          let lastIpPart = arr[j].target.toString().split('.')[arr[j].target.toString().split('.').length -1]
          if (parseInt(lastIpPartOfIndex) > parseInt(lastIpPart)) {
                let temp = arr[j]
                arr[j] = arr[i]
                arr[i] = temp
            }
        }
    }
    return arr;
}

如何使用选择排序功能将IP地址从大到小排序?

node.js ip node-modules ip-address selection-sort
1个回答
0
投票

我会使用内置的Array.prototype.sort函数和自定义的compareIps处理程序:

IP_NUM_OF_OCTETS = 4;

function compareIps (ip1, ip2) {
  const parsedOctets1 = ip1.split('.').map(s => parseInt(s));
  const parsedOctets2 = ip2.split('.').map(s => parseInt(s));
  for (let i = 0; i < IP_NUM_OF_OCTETS; i++) {
    if (parsedOctets1[i] !== parsedOctets2[i]) {
      return parsedOctets1[i] - parsedOctets2[i];
    }
  }
  return 0;
}

const ips = ['101.2.3.4' ,'101.2.3.3', '0.2.3.4', '0.2.3.4', '51.9.123.4'];
console.log(ips.sort(compareIps));

将打印:

[ '0.2.3.4', '0.2.3.4', '51.9.123.4', '101.2.3.3', '101.2.3.4' ]
© www.soinside.com 2019 - 2024. All rights reserved.