Go 指针和非指针方式实现冒泡排序算法

Go 指针和非指针方式实现冒泡排序算法

本文将用指针和非指针方式实现go的冒泡排序算法

指针实现
package main
import (
	"fmt"
)
func  bubbleSort(arr *[]int){
	length := len(*arr)
	for i :=0 ; i < length;i++{
		for  j := i+1 ; j< length; j++{
			if  (*arr)[j] < (*arr)[i] {
				(*arr)[j] ,(*arr)[i]= (*arr)[i],(*arr)[j]
			}
		}
	}
}
func main()  {
	items := []int{12,3,4,64,2,11,321,32,14,51,11,23,41,2,5,1,6,7,8,3,2,53,52,5235,3525,5235,23,5}
	fmt.Println("排序前",items)
	bubbleSort(&items)
	fmt.Println("排序后",items)
}
非指针方式实现
package main
import (
	"fmt"
)
func  bubbleSort(arr []int) []int{
	length := len(arr)
	items := make([]int,length)
	copy(items,arr)
	for i :=0 ; i < length;i++{
		for  j := i+1 ; j< length; j++{
			if  items[j] < items[i] {
				items[j] ,items[i]= items[i],items[j]
			}
		}
	}
	return items
}
func main()  {
	items := []int{12,3,4,64,2,11,321,32,14,51,11,23,41,2,5,1,6,7,8,3,2,53,52,5235,3525,5235,23,5}
	sortitems := bubbleSort(items)
	fmt.Println("排序前",items)
	fmt.Println("排序后",sortitems)
}

猜你喜欢

转载自blog.csdn.net/weixin_45760685/article/details/105044418
今日推荐