Quick sort,bubble sort,insertion sort in golang
阿新 • • 發佈:2019-01-05
Quick Sort
package main import ( "math/rand" "time" "fmt" ) func QuickSort(x []int,s int,t int) { if s>=t { return } i:=s j:=t k:=x[s] for i<j { for i<j && x[j]<=k { j-- } if i<j { x[i],x[j]=x[j],x[i] } for i<j && x[i]>=k { i++ } if i<j { x[i],x[j]=x[j],x[i] } } QuickSort(x,s,i-1) QuickSort(x,j+1,t) } func main() { rand.Seed(time.Now().Unix()) x:=make([]int,10) for i:=0; i<len(x); i++ { x[i]=rand.Intn(100) } fmt.Println(x) QuickSort(x,0,len(x)-1) fmt.Print(x) }
Bubble Sort
func BubbleSort(x []int) {
n:=len(x)
for i:=1; i<=n-1; i++ {
for j:=0; j<n-i; j++ {
if x[j]<x[j+1] {
x[j],x[j+1]=x[j+1],x[j]
}
}
}
}
Insertion Sort
func InsertionSort(x []int) { n:=len(x) for i:=1; i<n; i++ { for j:=i; j>0; j-- { if x[j-1]<x[j] { x[j-1],x[j]=x[j],x[j-1] } } } }