in reply to Algorithm Pop Quiz: Sorting
Oh bugger me, I had to see this at 1:00AM when I was about to go in for the night...
I'm not sure that I see a quicksort coming out of this. With the limitation on accessing the stack and all, plus no allowances for making arrays or new stacks, handling the recursion would be a nightmare. I once had to write a non-recursive implementation of quicksort as a class exercise, and it damn near drove me into the arms of the music department as a result.
Here's a bubblesort. I'm not sure how you count instructions. If I count every assignment, count each conditional as one (each of the two while's and an if), then a cond-clause as well (the else), plus one count for calls like pop, push and rotate_up, then I get somewhere around 24. That's probably not quite right, though, or your challenge would have been for a lower number.
Bubble-sort is still an O(N2) algorithm, though it is better in most cases than a selection sort. There is an early-termination form of the algorithm, but I'm already up past my bedtime. If I get a chance to look at this again before deadline, I'll see if I can adapt that. Big raspberries to the people who say that studying computer science in universities is a waste of time (and I know a lot of them at my day-job).
If I take complete leave of my senses, I'll see if I can remember that non-recursive q-sort...
--rjray
# Assume that rotate_up as defined in the original problem # statement has been defined. sub sordid { local $len = pop(@stack); local $bum = $len; local ($x, $y, $limit); while ($bum > 1) { $limit = $bum; while (--$limit) { $x = pop(@stack); $y = pop(@stack); if ($x gt $y) { push(@stack, $x); push(@stack, $y); } else { push(@stack, $y); push(@stack, $x); } rotate_up($bum); } # At end of the $limit loop, top element is the max, and # top+1 to end is semi-sorted. One more rotate_up() # is needed before moving the floor up one notch. rotate_up($bum); $bum--; } push(@stack, $len); } @stack = qw(d b f a e c 6); # <-- bottom .. top --> print "(@stack)\n"; # Prints: (d b f a e c 6) sordid(); print "(@stack)\n"; # Prints: (f e d c b a 6)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Algorithm Pop Quiz: Sorting
by Jasper (Chaplain) on Mar 25, 2002 at 14:08 UTC | |
by RMGir (Prior) on Mar 25, 2002 at 14:22 UTC | |
by Jasper (Chaplain) on Mar 25, 2002 at 14:51 UTC | |
by RMGir (Prior) on Mar 25, 2002 at 14:58 UTC | |
by clintp (Curate) on Mar 25, 2002 at 15:18 UTC | |
Improved Bubble-Sort (Re: Re: Algorithm Pop Quiz: Sorting)
by rjray (Chaplain) on Mar 25, 2002 at 23:31 UTC | |
Re: Re: Algorithm Pop Quiz: Sorting
by RMGir (Prior) on Mar 25, 2002 at 12:21 UTC |