
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort


Task

Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.

Use a sorting facility provided by the language/library, combined with your own callback comparison function.


Note:   Lexicographic order is case-insensitive.




DEFINE PTR="CARD"
 
PROC PrintArray(PTR ARRAY a INT size)
  INT i
 
  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    Print(a(i))
  OD
  Put(']) PutE()
RETURN
 
INT FUNC CustomComparator(CHAR ARRAY s1,s2)
  INT res
 
  res=s2(0) res==-s1(0)
  IF res=0 THEN
    res=SCompare(s1,s2)
  FI
RETURN (res)
 
INT FUNC Comparator=*(CHAR ARRAY s1,s2)
DEFINE JSR="$20"
DEFINE RTS="$60"
  [JSR $00 $00 ;JSR to address set by SetComparator
   RTS]
 
PROC SetComparator(PTR p)
  PTR addr
 
  addr=Comparator+1 ;location of address of JSR
  PokeC(addr,p)
RETURN
 
PROC InsertionSort(PTR ARRAY a INT size PTR compareFun)
  INT i,j
  CHAR ARRAY s
 
  SetComparator(compareFun)
  FOR i=1 TO size-1
  DO
    s=a(i)
    j=i-1
    WHILE j>=0 AND Comparator(s,a(j))<0
    DO
      a(j+1)=a(j)
      j==-1
    OD
    a(j+1)=s
  OD
RETURN
 
PROC Test(PTR ARRAY a INT size PTR compareFun)
  PrintE("Array before sort:")
  PrintArray(a,size)
  PutE()
 
  InsertionSort(a,size,compareFun)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN
 
PROC Main()
  PTR ARRAY a(24)
 
  a(0)="lorem" a(1)="ipsum" a(2)="dolor" a(3)="sit"
  a(4)="amet" a(5)="consectetur" a(6)="adipiscing"
  a(7)="elit" a(8)="maecenas" a(9)="varius"
  a(10)="sapien" a(11)="vel" a(12)="purus"
  a(13)="hendrerit" a(14)="vehicula" a(15)="integer"
  a(16)="hendrerit" a(17)="viverra" a(18)="turpis" a(19)="ac"
  a(20)="sagittis" a(21)="arcu" a(22)="pharetra" a(23)="id"
 
  Test(a,24,CustomComparator)
RETURN