1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| func quickSort(arr []int) { if arr == nil || len(arr) < 2 { return } process(arr, 0, len(arr) - 1) }
func process(arr []int, L, R int) { if L < R { left, right := partition(arr, L, R) process(arr, L, left) process(arr, right, R) } }
func partition(arr []int, L, R int) (int, int) { less, more := L - 1, R + 1 index := L value := arr[L + rand.Intn(R - L + 1)] for index < more { if arr[index] < value { arr[less + 1], arr[index] = arr[index], arr[less + 1] less++ index++ } else if arr[index] > value { arr[more - 1], arr[index] = arr[index], arr[more - 1] more-- } else { index++ } } return less, more }
|