Sorting algorithms/Pancake sort

From Rosetta Code
Revision as of 02:39, 5 April 2010 by Eriksiers (talk | contribs) (created with BASIC example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Sort an array of integers (of any convenient size) in ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:

Before:
6 7 8 9 2 5 3 4 1
After:
9 8 7 6 2 5 3 4 1

Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better.

Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended).

For more information on pancake sorting, see the Wikipedia entry.

See also: Number reversal game

BASIC

Works with: QBasic
Works with: FreeBASIC

<lang qbasic>RANDOMIZE TIMER

DIM nums(9) AS INTEGER DIM L0 AS INTEGER, L1 AS INTEGER, n AS INTEGER

'initial values FOR L0 = 0 TO 9

   nums(L0) = INT(RND * 32768)
   PRINT nums(L0);

NEXT PRINT

FOR L1 = 9 TO 1 STEP -1

   n = 0
   FOR L0 = 1 TO L1
       IF nums(n) < nums(L0) THEN n = L0
   NEXT
   IF (n < L1) THEN
       IF (n > 0) THEN
           FOR L0 = 0 TO (n \ 2)
               SWAP nums(L0), nums(n - L0)
           NEXT
       END IF
       FOR L0 = 0 TO (L1 \ 2)
           SWAP nums(L0), nums(L1 - L0)
       NEXT
   END IF
  
   FOR L0 = 0 TO 9
       PRINT nums(L0);
   NEXT
   PRINT

NEXT</lang>

Sample output:

27916 5928 23535 14711 32184 14621 21093 14422 29844 11093
11093 29844 14422 21093 14621 27916 5928 23535 14711 32184
14711 23535 5928 27916 14621 21093 14422 11093 29844 32184
11093 14422 21093 14621 14711 23535 5928 27916 29844 32184
5928 11093 14422 21093 14621 14711 23535 27916 29844 32184
14711 14621 5928 11093 14422 21093 23535 27916 29844 32184
14422 11093 5928 14621 14711 21093 23535 27916 29844 32184
5928 11093 14422 14621 14711 21093 23535 27916 29844 32184