0

go冒泡算法及简单优化

 2 years ago
source link: https://blog.leixin.wang/ce7d7117.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go冒泡算法及简单优化

发表于 2018-07-08

| 分类于 golang

| 0

| 浏览 次

字数统计: 265

|

阅读时长 ≈ 1

冒泡排序,在学习编程时最常见的一个排序算法。但在实际工作中会遇到一些坑。比如,如果接收到的是已经排好序的序列,再进行排序没有必要。

package main

import (
"fmt"
"math/rand"
"time"
)

/*
冒泡排序
*/
func bubble(ints []int) {
for i := 0; i < len(ints); i++ {
flag := 0//增加标记位
for j := 0; j < len(ints)-i-1; j++ {
if ints[j] > ints[j+1] {
ints[j], ints[j+1] = ints[j+1], ints[j]
flag++ //当发生数据交换,则修改标记位
}
}
if flag == 0 {
break //判断标记位是否修改,未修改则表示是顺序序列,跳出循环
}
}
}

func main() {
arrs := []int{}
/*生成100个1000以内的随机数*/
rand.Seed(time.Now().Unix())
for n := 0; n <= 100; n++ {
arrs = append(arrs, rand.Int()%1000)
}

/*go的优化,传入slice或者map,默认传入指针类型
所以这里直接将arrs作为传入传出参数使用*/
bubble(arrs)
fmt.Println(arrs)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK