@Golang数据结构和算法之排序
呃呃呃呃,单纯只是想没事看看,有空了在调整补充
package main
import "fmt"
/*
冒泡排序
bubbleSort(A[N])
flage = 1
while flage
flage = 0
for j=N-1 to 1
if A[j] < A[j-1]
change(A[j],A[j-1])
flage = 1
*/
func bubbleSort(A []int){
flag := true
for flag {
flag = false
for j := len(A); j > 0; j-- {
if A[j] < A[j-1] {
A[j], A[j-1] = A[j-1], A[j]
flag = true
}
}
}
}
func main() {
A:= [...]int{5, 2, 4, 6, 1, 3}
bubbleSort(A)
fmt.Println(A)
}
package main
import "fmt"
/*
插入排序
insertionSort(A[N])
for i=1 to n-1
v=A[i]
j=i-1
while j>=0 && A[j]>v
A[j+1]=A[j]
j--
A[j+1]=v
*/
func insertionSort(A []int){
for i := 1; i < len(A); i++ {
v := A[i]
j := i - 1
for j >= 0 && A[j] > v {
A[j+1] = A[j]
j--
}
A[j+1] = v
}
}
func main() {
A := [...]int{5, 2, 4, 6, 1, 3}
insertionSort(A[:])
fmt.Println(A)
}
package main
import "fmt"
/*
选择排序
selectionSort(A[N])
for i=0 to N-1{
minj = i
for j=i to N-1
if A[j] < A[minj]
minj = j
change(A[i],A[minj])
}
*/
func selectionSort(A []int){
for i := 0; i < len(A); i++ {
minj := i
for j := i; j < len(A); j++ {
if A[j] < A[minj] {
minj = j
}
}
A[i], A[minj] = A[minj], A[i]
}
}
func main() {
A := [...]int{5, 2, 4, 6, 1, 3}
selectionSort(A[:])
fmt.Println(A)
}
package main
import "fmt"
/*
归并排序
merge(A,left,mid,right)
n1 = mid-left
n2 = right - mid
for i = 0 to n1-1
L[i]=A[left+i]
for i=0 to n2-1
R[i]=A[mid+i]
L[n1]=Max
R[n2]=Max
i=0
j=0
for k=left to right-1
if L[i] <= R[j]
A[k]=L[i]
i=i+1
else
A[k]=R[j]
j=j+1
*/
func merge(A []int, left, mid, right int) {
L, R := make([]int, mid-left), make([]int, right-mid)
copy(L, A[left:mid])
copy(R, A[mid:right])
L = append(L, 100000)
R = append(R, 100000)
i, j := 0, 0
fmt.Println(L, R)
for k := left; k < right; k++ {
if L[i] <= R[j] {
A[k] = L[i]
i++
} else {
A[k] = R[j]
j++
}
}
}
/*
mergeSort(A[N],left,right)
if left+1 < right
mid = (left+right)/2
mergeSort(A,left,mid)
mergeSort(A,mid,right)
merge(A,left,mid,right)
*/
func mergeSort(A []int, left, right int) {
if left+1 < right {
mid := (left + right) / 2
mergeSort(A, left, mid)
mergeSort(A, mid, right)
merge(A, left, mid, right)
}
}
func main() {
A := [...]int{1, 5, 2, 4, 8}
mergeSort(A[:], 0, len(A))
fmt.Println(A)
}
package main
/*
分割
partition(A[N],p,r)
x = A[r]
i = p-1
for j=p to r-1
if A[j] <=x
i = i+1
change(A[i],A[j])
change(A[i+1],A[r])
return i+1
*/
func partition(A []int, p, r int) int {
x := A[r]
i := p - 1
for j := p; j < r-1; j++ {
if A[j] <= x {
i = i + 1
A[i], A[j] = A[j], A[i]
}
}
A[i+1], A[r] = A[r], A[i+1]
return i + 1
}
/*
快速排序
quickSort(A[N],p,r)
if p < r
q = partition(A,p,r)
quickSort(A,p,q-1)
quickSort(A,q+1,r)
*/
func quickSort(A []int, p, r int) {
if p < r {
q := partition(A,p,r)
quickSort(A,p,q-1)
quickSort(A,q+1,r)
}
}
func main() {
A := [...]int{5, 2, 4, 6, 1, 3}
insertionSort(A[:])
fmt.Println(A)
}