冒泡算法的实现:
func bubbleSort(arr []int) []int {
n := len(arr)
for i := 0; i < n-1; i++ {
for j:=0;j<n-1-i;j++{
if arr[j]>arr[j+1]{
arr[j],arr[j+1] = arr[j+1],arr[j]
}
}
}
return arr
}
选择排序的实现:
func selectSort(arr []int) []int {
n := len(arr)
for i:=0;i<n-1;i++{
index := i
for j:=i+1;j<n;j++{
if arr[index]>arr[j]{
index = j
}
}
arr[i],arr[index] = arr[index],arr[i]
}
return arr
}
go 快速排序实现
func quickSort(arr []int, start, end int) {
if start < end {
i, j := start, end
key := arr[(start+end)/2]
for i <= j {
for arr[i] < key {
i++
}
for arr[j] > key {
j--
}
if i <= j {
arr[i], arr[j] = arr[j], arr[i]
i++
j--
}
}
if start < j {
quickSort(arr, start, j)
}
if end > i {
quickSort(arr, i, end)
}
}
}
func main() {
arr := []int{3, 7, 9, 8, 38, 93, 12, 222, 45, 93, 23, 84, 65, 2}
quickSort(arr, 0, len(arr)-1)
fmt.Println(arr)
}
go 二分查找
func half(arr []int,target int) int {
start := 0
end := len(arr)
for start<= end {
middle := (start+end)/2
if target == arr[middle]{
return middle
}
if target >arr[middle]{
start = middle+1
}else{
end = middle-1
}
}
return -1
}