• golang 冒泡排序实现


    排序,顾名思义,就是把一坨数字按照某种特定的顺序排列好了,比如从小到大又或者从大到小。

    冒泡排序,冒泡嘛,形象一点儿,就是一个个泡泡往上涌,然后和“相邻的泡泡”比试,最后最小的泡泡浮到了水面上。既然是想要让小的从底部都涌到上面,那么为何不尝试一下最后往前呢?

    package main
    
    import(
    	"fmt"
    )
    
    //冒泡排序常规排序
    /*func Bubblesort(arr *[5]int)  {
    	
    	fmt.Println("排序前arr=",(*arr))
    	temp:=0
    	for i:=0; i<len(*arr)-1;i++{
    		for j:=0;j<len(*arr)-1-i;j++{
    			if(*arr)[j] > (*arr)[j+1]{
    				temp = (*arr)[j]
    				(*arr)[j] = (*arr)[j+1]
    				(*arr)[j+1] = temp
    			}
    		}
    	}
    
    	fmt.Println("排序后arr=",(*arr))
    }*/
    //冒泡排序 比上者排序更有优势,特殊情况arr:=[5]int{7,10,20,35,98}这种情况就无需所有再次遍历
    func Bubblesort(arr *[5]int)  {
    	fmt.Println("排序前arr=",(*arr))
    	temp:=0
    	swap:=true
    	for i:=0; i<len(*arr)&& swap==true;i++{
    		swap=false
    		for j:=len(*arr)-1; j > i; j--{
    			if(*arr)[j] < (*arr)[j-1]{
    				temp = (*arr)[j]
    				(*arr)[j] = (*arr)[j-1]
    				(*arr)[j-1] = temp
    				swap = true
    			}
    		}
    	}
    
    	fmt.Println("排序后arr=",(*arr))
    }
    
    func main()  {
    	arr:=[5]int{20,98,10,35,7}
    	Bubblesort(&arr)
    }
    

      

  • 相关阅读:
    centos配置WordPress(Apache+mysql+php)
    sublime text3配置Python2、Python3的编译环境
    Python3——字典
    Python3基础——函数
    Python3基础——递归
    Python3基础——字符串类型
    activiti会签直接写死人员
    delete执行速度优化
    C盘空间满了怎么办
    python运算符
  • 原文地址:https://www.cnblogs.com/setevn/p/14277468.html
Copyright © 2020-2023  润新知