Go 语言实现基本排序
目录
1. 冒泡排序 (BubbleSort)
func TestBubbleTest(t *testing.T) {
arr := []int{2, 3, 5, 1, 5, 7, 4}
bubbleSort(arr)
for i := 0; i < len(arr); i++ {
fmt.Print(arr[i])
}
}
func bubbleSort(arr []int) {
if arr == nil || len(arr) < 2 {
return
}
for i := len(arr); i > 0; i-- {
for j := 0; j < i-1; j++ {
if arr[j+1] < arr[j] {
Swap(arr, j+1, j)
}
}
}
}
2. 插入排序 (Insertion Sort)
func TestInsertSort(t *testing.T) {
arr := []int{2, 3, 5, 1, 5, 7, 4}
insetSort2(arr)
for i := 0; i < len(arr); i++ {
fmt.Printf("%d", arr[i])
}
}
func insetSort2(arr []int) {
if len(arr) < 2 || arr == nil {
return
}
for i := 1; i < len(arr); i++ {
for j := i - 1; j >= 0 && arr[j] > arr[j+1]; j-- {
Swap(arr, j, j+1)
}
}
}
func Swap(arr []int, pre int, cur int) {
tem := arr[pre]
arr[pre] = arr[cur]
arr[cur] = tem
}
3. 选择排序 (SelctionSort)
func TestSelectSort(t *testing.T) {
arr := []int{2, 3, 5, 1, 5, 7, 4}
selectionSort(arr)
fmt.Println(arr)
}
func selectionSort(arr []int) {
if arr ==nil && len(arr)<2{
return
}
for i := 0; i < len(arr); i++ {
for j := i+1; j < len(arr); j++ {
if arr[i]>arr[j] {
Swap(arr,i ,j)
}
}
}
}
4. 归并排序 (Merge Sort)
func TestMergeSort(t *testing.T) {
arr := []int{5, 4, 3, 2, 1}
mergeSort(arr)
}
func mergeSort(arr []int) {
if arr == nil || len(arr) < 2 {
return
}
prosess(arr, 0, len(arr)-1)
fmt.Println(arr)
}
func prosess(arr []int, l int, r int) {
if l == r {
return
}
m := l + ((r - l) >> 1)
prosess(arr, l, m)
prosess(arr, m+1, r)
merge(arr, l, m, r)
}
func merge(arr []int, l int, m int, r int) {
help := make([]int, r - l + 1)
i := 0
p := l
p2 := m + 1
for p <= m && p2 <= r {
if arr[p]<=arr[p2] {
help[i]=arr[p]
p++
}else {
help[i]=arr[p2]
p2++
}
i++
}
for p<=m {
help[i]=arr[p]
i++
p++
}
for p2<=r {
help[i]=arr[p2]
i++
p2++
}
for i := 0; i < len(help); i++ {
arr[l + i]=help[i]
}
}
5. 快速排序 (Quicksort)
import (
"fmt"
"testing"
)
func TestFastSort(t *testing.T) {
arr := []int{2, 3, 5, 1, 5, 7, 4}
fastSort(arr)
fmt.Println(arr)
}
func fastSort(arr []int) {
if arr==nil|| len(arr)<2 {
return
}
prosess2(arr,0,len(arr)-1)
}
func prosess2(arr []int, L int, R int) {
if L>R {
return
}
M:=partitition(arr,L,R)
prosess2(arr,L,M-1)
prosess2(arr,M+1,R)
}
func partitition(arr []int, L int, R int) int {
if L>R{
return -1
}
if L==R {
return L
}
lessEquals:=L-1
index:=L
for index<R{
if arr[index]<=arr[R] {
lessEquals++
Swap(arr,lessEquals,index)
}
index++
}
lessEquals++
Swap(arr,lessEquals,R)
return lessEquals;
}