用go语言来玩下冒泡排序

     用go语言来玩下冒泡排序, 主要是熟悉一下Go语法:

package main

import "fmt"

func bubble_sort(a []int){
    n := len(a)
    for i := 0; i < n - 1; i++ {
        for j := 0; j < n - 1 - i; j++ {
            if a[j] > a[j + 1]{
                a[j], a[j + 1] = a[j + 1], a[j]
            }
        }
    }
    
}

func print_arr(a []int){
    n := len(a)
    for i:= 0; i < n; i++ {
        fmt.Printf("%d ", a[i])
    }
    
    fmt.Printf("\n")
}

func main(){
    a := []int{4, 3, 1, 6, 2, 0, -1}
    print_arr(a)
    
    bubble_sort(a)
    print_arr(a)
}

        结果:

4 3 1 6 2 0 -1 
-1 0 1 2 3 4 6 
 

      可以看到, 在函数bubble_sort内部,是可以根据len函数来计算数组长度的, 而在C/C++中, 却做不到, 必须把长度n当参数传进去。

      顺便说下, 上面程序还可以优化。

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/81611492