guange

第 4871 号会员 /

回复了 jimmykuu 创建的主题: Go 排序代码悬赏

import (
    "testing"
)

func isLetter(a byte) int {
    if (a =='a' || a=='b' || a=='r') {
        return 1
    }
    return 0
}

func compare(a string, b string)(x int){
    as := []byte(a)
    bs := []byte(b)
    minLen := len(as)
    if len(bs)<minLen{
        minLen = len(bs)
    }

    x = 0 //默认相等
    for i :=0; i <minLen ; i++ {
        if(as[i]==bs[i]){
            continue
        }
        x = isLetter(bs[i]) - isLetter(as[i])
        if x != 0{
            return
        }

        if(as[i]>bs[i]){
            return 1
        } else if(as[i]<bs[i]) {
            return -1
        }

    }
    if x == 0{
        if(len(as) >minLen && isLetter(as[minLen])==1){
            x = -1
        } else if(len(bs) >minLen && isLetter(bs[minLen])==1){
            x = 1
        } else {
            x = len(as)-len(bs)
        }
    }
    return x
}

func VersionSort(versions []string) []string {
    //普通的冒泡 
    for i := 0; i<len(versions);i++  {
        for j := i+1; j<len(versions);j++  {
            if(compare(versions[i], versions[j])>0){
                versions[i], versions[j] = versions[j], versions[i]
            }
        }
    }
    return versions
}

func Test_VersionSort(t *testing.T)  {
    inputs := []string {"1.6beta1", "1.5rc1", "1.5beta2", "1.5beta1", "1.5.1", "1.5", "1.4rc2", "1.4rc1", "1.4beta1", "1.4.2", "1.4.1", "1.4", "1.3rc2", "1.3rc1", "1.3beta2", "1.3beta1", "1.3.3", "1.3.2", "1.3.1", "1.3", "1.2rc5", "1.2rc4", "1.2rc3", "1.2rc2", "1.2rc1", "1.2.2", "1.2.1", "1.2", "1.1.2", "1.1.1", "1.1", "1.0.3", "1.0.2", "1.5.2", "1.5alpha1"}
    outputs := []string {"1.0.2", "1.0.3", "1.1", "1.1.1", "1.1.2", "1.2rc1", "1.2rc2", "1.2rc3", "1.2rc4", "1.2rc5", "1.2", "1.2.1", "1.2.2", "1.3beta1", "1.3beta2", "1.3rc1", "1.3rc2", "1.3", "1.3.1", "1.3.2", "1.3.3", "1.4beta1", "1.4rc1", "1.4rc2", "1.4", "1.4.1", "1.4.2", "1.5alpha1", "1.5beta1", "1.5beta2", "1.5rc1", "1.5", "1.5.1", "1.5.2", "1.6beta1"}

    a := VersionSort(inputs)
    for i, num := range a {
        if num != outputs[i]{
            t.Error( "sort different")
        }
    }
}