]> Cypherpunks repositories - gostls13.git/commitdiff
Sort: reduced stack depth to lg(n) in quickSort
authorStefan Nilsson <snilsson@nada.kth.se>
Thu, 2 Dec 2010 17:18:20 +0000 (09:18 -0800)
committerRobert Griesemer <gri@golang.org>
Thu, 2 Dec 2010 17:18:20 +0000 (09:18 -0800)
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

src/pkg/sort/sort.go

index 2abe22d5c755c530c0497f2d80672380134d89eb..02e647fca9ab1c87bad5d72ebdbf89eda68a9086 100644 (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)
        }
 }