1
0
mirror of https://github.com/golang/go synced 2024-11-22 01:14:40 -07:00

Sort: reduced stack depth to lg(n) in quickSort

Doing the tail recursion elimination explicitly
seems safer than leaving it to the compiler;
the code is still clean and easy to understand.

R=r, r2, gri
CC=golang-dev
https://golang.org/cl/3373041
This commit is contained in:
Stefan Nilsson 2010-12-02 09:18:20 -08:00 committed by Robert Griesemer
parent 4e40a03682
commit 6f1835dce0

View File

@ -122,11 +122,19 @@ func doPivot(data Interface, lo, hi int) (midlo, midhi int) {
}
func quickSort(data Interface, a, b int) {
if b-a > 7 {
for b-a > 7 {
mlo, mhi := doPivot(data, a, b)
quickSort(data, a, mlo)
quickSort(data, mhi, b)
} else if b-a > 1 {
// Avoiding recursion on the larger subproblem guarantees
// a stack depth of at most lg(b-a).
if mlo-a < b-mhi {
quickSort(data, a, mlo)
a = mhi // i.e., quickSort(data, mhi, b)
} else {
quickSort(data, mhi, b)
b = mlo // i.e., quickSort(data, a, mlo)
}
}
if b-a > 1 {
insertionSort(data, a, b)
}
}