From b0c9bc7d4131c8a6b8ac26db9e485977b385cdeb Mon Sep 17 00:00:00 2001 From: Ahmet Inan Date: Sat, 9 Mar 2024 18:57:47 +0100 Subject: [PATCH] got rid of the recursion --- quick_select.hh | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/quick_select.hh b/quick_select.hh index be7b6be..31ae9b0 100644 --- a/quick_select.hh +++ b/quick_select.hh @@ -33,14 +33,16 @@ static int partition(TYPE *a, int l, int h) template static TYPE select(TYPE *a, int l, int h, int k) { - if (l == h) - return a[l]; - int i = partition(a, l, h); - if (i == k) - return a[i]; - if (i > k) - return select(a, l, i-1, k); - return select(a, i+1, h, k); + while (l < h) { + int i = partition(a, l, h); + if (k == i) + return a[k]; + if (k < i) + h = i - 1; + else + l = i + 1; + } + return a[l]; } }