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]; } }