diff mbox series

[v2,1/2] stdlib: Optimize number of calls to comparison function in qsort

Message ID 20231205032207.3183789-2-visitorckw@gmail.com
State New
Headers show
Series stdlib: Optimize number of calls to comparison function in qsort | expand

Commit Message

Kuan-Wei Chiu Dec. 5, 2023, 3:22 a.m. UTC
The current heapsort implementation in the siftdown function follows
the standard textbook version, necessitating two comparisons at each
level. Transitioning to the Bottom-up heapsort version allows us to
decrease the required comparisons to just one per level. On average,
this modification significantly reduces the comparison count from
2nlog2(n) - 3n + O(n) to nlog2(n) + 0.37*n + O(n).

Refs:
  BOTTOM-UP-HEAPSORT, a new variant of HEAPSORT beating, on an average,
  QUICKSORT (if n is not very small)
  Ingo Wegener
  Theoretical Computer Science, 118(1); Pages 81-98, 13 September 1993
  https://doi.org/10.1016/0304-3975(93)90364-Y

Signed-off-by: Kuan-Wei Chiu <visitorckw@gmail.com>
---
Changes from v1:
* Use a more concise title.
* Correct the error in asymptotic notation from little-o to big-O.

 stdlib/qsort.c | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)
diff mbox series

Patch

diff --git a/stdlib/qsort.c b/stdlib/qsort.c
index 62477010b6..0d924f5e2d 100644
--- a/stdlib/qsort.c
+++ b/stdlib/qsort.c
@@ -132,26 +132,26 @@  static inline void
 siftdown (void *base, size_t size, size_t k, size_t n,
 	  enum swap_type_t swap_type, __compar_d_fn_t cmp, void *arg)
 {
-  /* There can only be a heap condition violation if there are
-     children.  */
-  while (2 * k + 1 <= n)
-    {
-      /* Left child.  */
-      size_t j = 2 * k + 1;
-      /* If the right child is larger, use it.  */
-      if (j < n && cmp (base + (j * size), base + ((j + 1) * size), arg) < 0)
-	j++;
-
-      /* If k is already >= to its children, we are done.  */
-      if (j == k || cmp (base + (k * size), base + (j * size), arg) >= 0)
-	break;
+  size_t i, j;
+
+  /* Find the sift-down path all the way to the leaves. */
+  for (i = k; j = 2 * i + 1, j + 1 <= n;)
+    i = cmp (base + j * size, base + (j + 1) * size, arg) >= 0 ? j : (j + 1);
 
-      /* Heal the violation.  */
-      do_swap (base + (size * j), base + (k * size), size, swap_type);
+  /* Special case for the last leaf with no sibling. */
+  if (j == n)
+    i = j;
 
-      /* Swapping with j may have introduced a violation at j.  Fix
-	 it in the next loop iteration.  */
-      k = j;
+  /* Backtrack to the correct location. */
+  while (i != k && cmp (base + k * size, base + i * size, arg) > 0)
+    i = (i - 1) / 2;
+
+  /* Shift the element into its correct place. */
+  j = i;
+  while (i != k)
+    {
+      i = (i - 1) / 2;
+      do_swap (base + i * size, base + j * size, size, swap_type);
     }
 }