美文网首页
go算法实现

go算法实现

作者: 苏州运维开发 | 来源:发表于2018-04-14 17:17 被阅读0次

    1.简易的桶排序

    package main
    
    import (
        "fmt"
    )
    
    func main(){
        sortdata := []int{5,54,3,9,47,3,6,0,5,3,11,10,68,3}
        contain := make([]int,100)
        for _,i := range sortdata{
            contain[i]++
        }
        for k,sdata := range contain{
            if sdata > 0{
                for t:=0;t<sdata;t++{
                    fmt.Println(k)
                }
            }
        }
    }
    

    2.冒泡排序

    package main
    
    import (
        "fmt"
    )
    
    func main(){
        sortdata := []int{5,54,3,9,47,3,6,0,5,3,11,10,68,3}
        for j:=0;j<len(sortdata);j++ {
            for i := 0; i < len(sortdata)-1; i++ {
                if sortdata[i] < sortdata[i+1] {
                    sortdata[i], sortdata[i+1] = sortdata[i+1], sortdata[i]
                }
            }
        }
        fmt.Println(sortdata)
    }
    

    3.求整数二进制表示中1的个数

    package main
    
    import (
        "fmt"
    )
    
    
    
    func main()  {
        s := 139
        fmt.Printf("%08b\n",s)
        fmt.Println(GetOneNum(s))
        fmt.Println(CalcOneNum(s))
    }
    
    func GetOneNum(a int) int  {
        num := 0
        for {
            if a == 0 {
                break
            } else {
                a = a & (a - 1)
                num++
            }
        }
        return num
    }
    
    func CalcOneNum(a int) int {
        a = ((a & 0xAAAA) >> 1) + (a & 0x5555)
        a = ((a & 0xCCCC) >> 2) + (a & 0x3333)
        a = ((a & 0xF0F0) >> 4) + (a & 0x0F0F)
        a = ((a & 0xFF00) >> 8) + (a & 0x00FF)
        return a
    }
    

    相关文章

      网友评论

          本文标题:go算法实现

          本文链接:https://www.haomeiwen.com/subject/rvblkftx.html