break it up and read
This is a very casual sort of name algorithm, it's me I'll call him slime sort sunglass (▔,▔) deny
Principle
The sort of goblin is also a sort of exchange. It only makes a comparison, in this round comparison, encountered the comparison of the previous element large on the back of a continuation of the comparison, encountering a smaller than the previous face value of the exchange, and move forward one bit.
Complexity of
For the queue that already has an ordinal number, the Goblin ends up just from the beginning to the end, so the best time is O (n), and the average time complexity is also the same as the Bubble sort O (n^2).
Code
package mainimport ( "time" "fmt" "math/rand")func main() { var length = 10 var list []int // 以时间戳为种子生成随机数,保证每次运行数据不重复 r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < length; i++ { list = append(list, int(r.Intn(1000))) } fmt.Println(list) gnome := 1 // 地精从第二个坑位开始向最后一个坑走过去 for gnome < length { // 如果地精发现自己这个坑位的值不比前面一个坑位的小,就继续向下个坑位走过去 if list[gnome] >= list[gnome-1] { gnome++ } else { // 如果比前个坑位值小,就交换两个坑位的值,然后再回到前一个坑位 list[gnome], list[gnome-1] = list[gnome-1], list[gnome] if gnome > 1 { gnome-- } fmt.Println(list) } }}
Run results
[Golang] Data structure-Sort by goblin