题目:
有一组版本号如下
['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5']。
现在需要对其进行排序,排序的结果为 ['4.3.5','4.3.4.5','2.3.3','0.302.1','0.1.1']
解题思路
由题目可知,版本号是字符串,需要把字符串切割成数字,最终是通过比较数字来排序。
加权比较法
通过对数字位置,当成个十百千位的位置,乘以一个常量倍数,得到结果来比较,最后通过sort排序。
const input = ['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5']
const maxLen = Math.max(...input.map(item => item.split('.').length))
const p = 1000
const reducer = (prev, curr, index) => prev + +curr * Math.pow(p, maxLen - index - 1)
const gen = (arr) => arr.split('.').reduce(reducer, 0)
input.sort((a, b) => {
return gen(b) > gen(a) ? 1 : -1
})
console.log(input) // [ '4.3.5', '4.3.4.5', '4.2', '2.3.3', '0.302.1', '0.1.1' ]
需要注意:常量p需要大于分割后的数字至少一个量级。
如果 p=10 ,那么,会出现0.302.1 会大于 0.1.1
循环比较法
如果当前版本号相同则比较下一位;如果版本号位数不相等而前几位值一致则认为位数多的版本号大。
const input2 = ['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5']
input2.sort((a, b) => {
let i = 0
let arr1 = a.split('.')
let arr2 = b.split('.')
while(true) {
let s1 = arr1[i]
let s2 = arr2[i]
i++
if(typeof s1 === 'undefined' || typeof s2 === 'undefined') {
return arr2.length - arr1.length
}
if(s1 === s2) continue
return s2 - s1
}
})
console.log(input2); // [ '4.3.5', '4.3.4.5', '4.2', '2.3.3', '0.302.1', '0.1.1' ]


被折叠的 条评论
为什么被折叠?



