From 2540b28ca3b2b5e4649d9d5cc57c5061755bf4af Mon Sep 17 00:00:00 2001 From: Stephen Heumann Date: Wed, 15 Feb 2023 22:04:10 -0600 Subject: [PATCH] Avoid excessively deep recursion in qsort. It could have O(n) recursion depth for some inputs (e.g. if already sorted or reverse sorted), which could easily cause stack overflows. Now, recursion is only used for the smaller of the two subarrays at each step, so the maximum recursion depth is bounded to log2(n). --- stdlib.asm | 26 ++++++++++++++++++-------- stdlib.macros | 12 ++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/stdlib.asm b/stdlib.asm index 329c67b..20f63f5 100644 --- a/stdlib.asm +++ b/stdlib.asm @@ -767,10 +767,10 @@ right equ 5 right address csubroutine (4:first,4:last),8 - phb +sr0 phb phk plb -sr0 lda last+2 if last <= first then quit + lda last+2 if last <= first then quit cmp first+2 bne sr1 lda last @@ -825,15 +825,24 @@ sr5 blt sr2 ph4