Click to See Complete Forum and Search --> : non-recursive quicksort


nanu2010
March 18th, 2005, 06:04 PM
can you give me a non recursive version of quicksort that uses a stack. the version should store at the stack indicies[i,j] of subarrays that have not been sorted yet.
what is the number of [i,j] pairs, non-sorted subarrays that can belong to stack simultaneously.

cma
March 20th, 2005, 01:59 PM
Any particular language? Here's one implementation in Java paraphrased from Robert Sedgewicks data structure's book:

static void quicksort(ITEM[] a, int l, int r)
{ Stack S = new Stack(50);
S.push(l); S.push(r);

while (!S.empty())
{
r = S.pop(); l = S.pop();

if (r <= l) continue;

int i = partition(a, l, r);

if (i-l > r-i) { S.push(l); S.push(i-1); }

S.push(i+1); S.push(r);

if (r-i >= i-l) { S.push(l); S.push(i-1); }
}
}