//快速排序,空介面//1 取參考點pivot: arr[low] arr[mid] arr[high]的中位元//2 將pivot放置合適位置//3 二分排序//4 待排序元素個數低於4個普通排序演算法//5 go語言可以直接交換,不需要swappackage mySort1import ( "fmt" "log")func median3(arr []interface{}, low, high int) (pivot interface{}) { //var pivot int mid := (low + high) / 2 //arr[low]放置三者最小值 if !compare(arr[low], arr[mid]) { arr[low], arr[mid] = arr[mid], arr[low] } if !compare(arr[low], arr[high]) { arr[low], arr[high] = arr[high], arr[low] } //arr[high]放置三者最大者 if !compare(arr[mid], arr[high]) { arr[mid], arr[high] = arr[high], arr[mid] } pivot = arr[mid] //交換arr[high-1]為arr[mid]值 arr[mid], arr[high-1] = arr[high-1], arr[mid] //返回參考值pivot return pivot}//QuickSort在mySort1包中func QuickSort(arr []interface{}, low, high int) { if low > high || high > (len(arr)-1) { log.Panicln("input error: low > high") } if (low + 3) <= high { pivot := median3(arr, low, high) //fmt.Println("pivot: ", pivot) //fmt.Println("pivot arr: ", arr) i, j := low+1, (high - 2) for { //左側 for { if compare(arr[i], pivot) { i++ } else { break } } //fmt.Println("arr[i]: ", arr[i]) //右側 for { if !compare(arr[j], pivot) { j-- } else { break } } //fmt.Println("arr[j]: ", arr[j]) //將大數交換至pivot右側 //將小數交換至pivot左側 if i < j { arr[i], arr[j] = arr[j], arr[i] } else { break //pivot找到合適位置 } } //pivot放置合適位置 arr[i], arr[high-1] = arr[high-1], arr[i] //fmt.Println("arr: ", arr) //分 QuickSort(arr, low, i-1) QuickSort(arr, i+1, high) } else { //待排序元素個數低於4個,simpleSort函數處理 simpleSort(arr, low, high) }}func simpleSort(arr []interface{}, low, high int) { if (high - low + 1) < 1 { fmt.Println("arr is empty") } if (high - low + 1) == 1 { } if (high - low + 1) == 2 { if !compare(arr[low], arr[high]) { arr[low], arr[high] = arr[high], arr[low] } } if (high - low + 1) == 3 { median3(arr, low, high) }}//比較空介面參數大小//用於mergeSort及其他排序演算法package mySort1import ( "log")//compare函數可以放置到其他pakcage這樣其他排序演算法可以調用//本算例compare放置在$GOPATH/src/mySort1包中//若compare與quickSort在同一包中可直接調用func compare(left, right interface{}) bool { switch left.(type) { //待排序數組轉為相應類型並比較 //空介面無比較 case int: if left.(int) < right.(int) { return true } else { return false } case float32: if left.(float32) < right.(float32) { return true } else { return false } case float64: if left.(float64) < right.(float64) { return true } else { return false } default: log.Panicln("ilegal type: int float32 float64") } return false}//quickSort函數調用樣本//mergeSort用法樣本package mainimport ( "fmt" "mySort1")func main() { //test quickSort: int float32 float64 quickSortTest()}func quickSortTest() { //arr1 := []int{4, 2, 1, 3, 5, 0, 8, 20, 100, 44, 50} arr1 := []float32{4.0, 2.1, 1.1, 3.2, 5, 0, 8, 20, 100.5, 44, 50} var arr = make([]interface{}, len(arr1)) for i, _ := range arr { arr[i] = arr1[i] } fmt.Println("before meidan3: ", arr) mySort1.QuickSort(arr, 0, len(arr)-1) fmt.Println("after meidan3: ", arr)}
本文為基於go語言的快速排序演算法,歸併排序演算法及go語言defer用法見:https://github.com/Beginner18/myBaseCode.git
defer: src/defer
排序演算法: src/mySort1
291 次點擊 ∙ 1 贊