Skip to content
Snippets Groups Projects
Commit 6f1835dc authored by Stefan Nilsson's avatar Stefan Nilsson Committed by Robert Griesemer
Browse files

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
parent 4e40a036
No related branches found
No related tags found
No related merge requests found
...@@ -122,11 +122,19 @@ func doPivot(data Interface, lo, hi int) (midlo, midhi int) { ...@@ -122,11 +122,19 @@ func doPivot(data Interface, lo, hi int) (midlo, midhi int) {
} }
func quickSort(data Interface, a, b int) { func quickSort(data Interface, a, b int) {
if b-a > 7 { for b-a > 7 {
mlo, mhi := doPivot(data, a, b) mlo, mhi := doPivot(data, a, b)
quickSort(data, a, mlo) // Avoiding recursion on the larger subproblem guarantees
quickSort(data, mhi, b) // a stack depth of at most lg(b-a).
} else if b-a > 1 { 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) insertionSort(data, a, b)
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment