package main
import "fmt"
// 快速排序+二分查找
// 快速排序
func QuickSort(arr []int) []int {
length := len(arr)
if length <= 1 {
return arr
} else {
spiltData := arr[0]
low := make([]int, 0, 0)
mid := make([]int, 0, 0)
higth := make([]int, 0, 0)
//mid = append(mid, spiltData)
for i:=0; i<length; i++ {
if arr[i] > spiltData {
higth = append(higth, arr[i])
} else if arr[i] < spiltData {
low = append(low, arr[i])
} else {
mid = append(mid, arr[i])
}
}
higth, low = QuickSort(higth), QuickSort(low)
return append(append(low, mid...), higth...)
}
}
// 二分查找
func binSearch(arr []int, data int) int {
low, hight := 0, len(arr)-1 // 找到最左和最右下标
for low <= hight {
mid := (low + hight)/2
if data > arr[mid] {
low = mid + 1
} else if data < arr[mid] {
hight = mid - 1
} else {
return mid
}
}
return -1
}
func main() {
arr := []int{2, 3, 1, 5, 3, 7, 0}
fmt.Println("未排序:", arr)
arr1 := QuickSort(arr)
fmt.Println("排序后:", arr1)
index := binSearch(arr1, 7)
if index == -1 {
fmt.Println("没找到!")
} else {
fmt.Printf("找到数据%d, 下标为%d。", arr1[index], index)
}
}
网友评论