How to resolve the algorithm Sort an array of composite structures step by step in the Action! programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sort an array of composite structures step by step in the Action! programming language

Table of Contents

Problem Statement

Sort an array of composite structures by a key.

For example, if you define a composite structure that presents a name-value pair (in pseudo-code): and an array of such pairs: then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sort an array of composite structures step by step in the Action! programming language

Source code in the action! programming language

DEFINE PTR="CARD"
DEFINE PAIR_SIZE="4"
DEFINE PAIR_COUNT="1"

TYPE Pair=[PTR name,value]

BYTE ARRAY pairs(100)
BYTE count=[0]

PTR FUNC GetItemAddr(INT index)
  PTR addr

  addr=pairs+index*PAIR_SIZE
RETURN (addr)

PROC PrintArray()
  INT i
  Pair POINTER p

  Put('[)
  FOR i=0 TO count-1
  DO
    IF i>0 THEN Put(' ) FI
    p=GetItemAddr(i)
    PrintF("(%S,%S)",p.name,p.value)
  OD
  Put(']) PutE()
RETURN

PROC Append(CHAR ARRAY n,v)
  Pair POINTER dst

  dst=GetItemAddr(count)
  dst.name=n
  dst.value=v
  count==+1
RETURN

PROC InitData()
  Append("Warsaw","Poland")
  Append("Prague","Czech Republic")
  Append("London","United Kingdom")
  Append("Paris","France")
  Append("Madrit","Spain")
  Append("Berlin","Germany")
  Append("Rome","Italy")
  Append("Moscow","Russia")
  Append("Budapest","Hungary")
RETURN

PROC Sort()
  INT i,j,minpos
  CHAR ARRAY tmp
  Pair POINTER p1,p2

  FOR i=0 TO count-2
  DO
    minpos=i
    FOR j=i+1 TO count-1
    DO
      p1=GetItemAddr(minpos)
      p2=GetItemAddr(j)
      IF SCompare(p1.name,p2.name)>0 THEN
        minpos=j
      FI
    OD
    
    IF minpos#i THEN
      p1=GetItemAddr(minpos)
      p2=GetItemAddr(i)
      tmp=p1.name p1.name=p2.name p2.name=tmp
      tmp=p1.value p1.value=p2.value p2.value=tmp
    FI
  OD
RETURN

PROC Main()
  InitData()
  PrintE("Array before sort:")
  PrintArray() PutE()
  
  Sort()
  PrintE("Array after sort:")
  PrintArray()
RETURN

  

You may also check:How to resolve the algorithm Bulls and cows step by step in the VTL-2 programming language
You may also check:How to resolve the algorithm Exponentiation order step by step in the Ruby programming language
You may also check:How to resolve the algorithm Pig the dice game step by step in the J programming language
You may also check:How to resolve the algorithm Named parameters step by step in the Julia programming language
You may also check:How to resolve the algorithm Poker hand analyser step by step in the Go programming language