Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

算法:版本号排序 #4

Open
Liqiuyue9597 opened this issue Jul 30, 2020 · 2 comments
Open

算法:版本号排序 #4

Liqiuyue9597 opened this issue Jul 30, 2020 · 2 comments

Comments

@Liqiuyue9597
Copy link
Owner

versions是一个项目的版本号列表,因多人维护,不规则 var versions=['1.45.0','1.5','6','3.3.3.3.3.3.3'] 要求从小到大排序,注意'1.45'比'1.5'大 。var sorted=['1.5','1.45.0','3.3.3.3.3.3','6']

@Liqiuyue9597
Copy link
Owner Author

function versionSort(arr) {
   //1.
  // 先将版本号每一位放到数组保存
  var temp = arr.map(v => v.split("."))
  
  //利用sort属性排序传入规则函数
  function rule(a, b) {
    var j = 0
    var minLen = Math.min(a.length, b.length)
    
    while (j < minLen) {
      if (parseInt(a[j]) > parseInt(b[j])) {
        return 1
      } else if (parseInt(a[j]) < parseInt(b[j])) {
        return -1
      }
      j++
    }

    // 遇到1.5与1.5.5的情况上面无法判断
    if (minLen == a.length) {
      return -1
    } else if (minLen == b.length) {
      return 1
    }
  }

  // 将比较后的版本从数组形式转为.的形式
  return temp.sort(rule).map(v => v.join("."))
  
  //2.同样的道理,写法更简单
  function rule(a, b) {
    var arr1 = a.split(".")
    var arr2 = b.split(".")
    var i = 0
    while (true) {
      var s1 = arr1[i],
        s2 = arr2[i++]
      if (s1 === undefined || s2 === undefined) return arr1.length - arr2.length //1.5与1.5.5的情况
      if (s1 === s2) continue  //相等就继续循环
      return s1 - s2 
    }
  }
  return arr.sort(rule)
}

@Liqiuyue9597
Copy link
Owner Author

遇到两次

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant