package main import "fmt" //shellsort func Shellsort(arr []int) { var i,j,h int N := len(arr) for h = N/2; h >=0; h=h/2 { for i = h; i <N; i++ { temp := arr[i] for j = i-h; j >= 0; j -= h { if temp < arr[j] { arr[j+h] = arr[i] } else { break } } arr[j+h] = temp } } } //quicksort func Quicksort(arr []int) { arrlen := len(arr)-1 seperatesort(arr, 0, arrlen) } func seperatesort(arr []int, start, end int) { if start >= end { return } i := partition(arr, start, end) seperatesort(arr, start, i-1) seperatesort(arr, i+1, end) } func partition(arr []int, start, end int) int{ //选取最后一位当对比数字 pivot := arr[end] var i = start for j := start; j < end; j++ { if arr[j] < pivot { arr[i], arr[j] = arr[j], arr[i] i++ } } arr[i], arr[end] = arr[end], arr[i] return i } //mergesort func MergeSort(arr []int) { mergeSort(arr, 0, len(arr)-1) } func mergeSort(arr []int, start, end int) { if start >= end { return } mid := (start + end)/2 mergeSort(arr, start, mid) mergeSort(arr, mid+1, end) merge(arr, start, mid, end) } func merge(arr []int, start, mid, end int) { tmparr := make([]int, end-start+1) i := start j := mid+1 k := 0 for ; i <= mid && j <= end; k++ { if arr[i] < arr[j] { tmparr[k] = arr[i] i++ } else { tmparr[k] = arr[j] j++ } } for ; i <= mid; i++ { tmparr[k] = arr[i] k++ } for ; j <= end; j++ { tmparr[k] = arr[j] k++ } copy(arr[start:end+1], tmparr) } //插入排序 func Insertsort(a []int, n int) { if n <= 1 { return } for i:= 1; i < n; i++ { temp := a[i] j := i-1 for ; j >= 0; j-- { if a[j] > temp { a[j+1] = a[j] } else { break } } a[j+1] = temp } } //冒泡排序 func Bubblesort(a []int, n int) { if n <= 1 { return } for i := 0; i < n; i++ { flag := false for j := 0; j < n-i-1; j++ { if a[j] > a[j+1] { a[j],a[j+1] = a[j+1], a[j] flag = true } } if flag == true { break } } } //选择排序 func Selectsort(a []int, n int) { if n <= 1 { return } for i := 0; i < n; i++ { minindex := i for j := i+1; j < n; j++ { if a[minindex] > a[j] { minindex = j } } a[i], a[minindex] = a[minindex], a[i] } } func main() { var a = []int{10, 4, 40, 5, 60} MergeSort(a) fmt.Println(a) Insertsort(a, len(a)) fmt.Println(a) Bubblesort(a, len(a)) fmt.Println(a) Selectsort(a, len(a)) fmt.Println(a) Quicksort(a) fmt.Println(a) Shellsort(a) fmt.Println(a) }
go_sort
最新推荐文章于 2024-01-18 02:04:00 发布