PROGRAM-ID. H. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. DATA DIVISION. WORKING-STORAGE SECTION. 01 Q. 05 n PIC 9(4). 05 i PIC 9(4). 05 j PIC 9(4). 05 k PIC 9(4). 05 t PIC A(10). 05 c PIC A(10). 05 r PIC A(10).
05 p PIC A(5000). 05 w OCCURS 1000 PIC A(10). PROCEDURE DIVISION. ACCEPT n. PERFORM VARYING i FROM 1 BY 1 UNTIL i > n ACCEPT w(i) END-PERFORM IF n = 1 GO TO M. PERFORM VARYING i FROM 1 BY 1 UNTIL i > n - 1 
MOVE i TO k PERFORM VARYING j FROM i BY 1 UNTIL j + 1 > n IF w(j + 1) < w(k) COMPUTE k = j + 1 END-IF END-PERFORM IF k NOT = i MOVE w(k) TO t MOVE w(i) TO w(k) MOVE t TO w(i) END-IF END-PERFORM. M. PERFORM VARYING i FROM 1 BY 1 UNTIL i > n 
IF W(i) NOT = SPACES MOVE REVERSE(TRIM(w(i))) TO r PERFORM VARYING j FROM i BY 1 UNTIL j > n - 1 IF w(j + 1) = r MOVE CONCATENATE(TRIM(p), TRIM(w(i))) TO p MOVE SPACES TO w(j + 1) EXIT PERFORM END-IF END-PERFORM IF j >= n - 1 AND w(i) = r
IF c = SPACES OR r < c MOVE r TO c END-IF END-IF END-IF END-PERFORM IF p NOT = SPACES DISPLAY TRIM(p) WITH NO ADVANCING. IF c NOT = SPACES DISPLAY TRIM(c) WITH NO ADVANCING. IF p NOT = SPACES DISPLAY REVERSE(TRIM(p)) WITH NO ADVANCING.
.
