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地址从大到小排序?
我会使用内置的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' ]