Lindo Systems

MODEL:
! Illustrating sorting in LINGO; ! (Sortin.lg4);
! Keywords: Sorting, Rank order;
SETS:
 CITY:
  LAT,     ! Its latitude;
  SORTPOS, ! Its rank in distance from equator;
  SORTORD; ! The item in position k in sorted order;
ENDSETS

DATA:
 CITY = LONDON, PARIS, NYC,   LA, MOSCOW, TOKYO;
 LAT =   51.3    48.5  40.4  34.1  55.5    35.4;
ENDDATA

CALC:
 @SET('TERSEO',2); ! Turn off default output;

 ! Get the rank order by latitude of each city
   SORTPOS(i) = sort position of LAT(i), increasing order;
 SORTPOS = @RANK(LAT);

 @WRITE('  City    Latitude  Rank', @NEWLINE(1));
  @FOR( CITY(i):
     @WRITE( @FORMAT(CITY(i),'8s'),'   ', LAT(i),'       ', SORTPOS(i), @NEWLINE(1));
   );

  ! Put in sorted order increasing, in vector SORTORD;
  ! SORTORD(i) = item in position i;
  @FOR( CITY(i):
     SORTORD(SORTPOS(i)) = i;
       );
  
  @WRITE(@NEWLINE(1),' Cities  in Latitude increasing order',@NEWLINE(1));
  @FOR( CITY(i):
     @WRITE( @FORMAT( CITY( SORTORD( i)),'8s'),'     ', LAT(SORTORD(i)), @NEWLINE(1));
   );

  ! Put in sorted order decreasing, in vector SORTORD;
  NCITY = @SIZE( CITY);
  @FOR( CITY(i):
  ! To put in decreasing order, use;
    SORTORD( NCITY + 1 - SORTPOS( i)) = i;
       );
  
  @WRITE(@NEWLINE(1),' Cities  in Latitude decreasing order',@NEWLINE(1));
  @FOR( CITY(i):
     @WRITE( @FORMAT(CITY(SORTORD(i)),'8s'),'     ', LAT(SORTORD(i)), @NEWLINE(1));
   );

ENDCALC