How to resolve the algorithm Order by pair comparisons step by step in the Action! programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Order by pair comparisons step by step in the Action! programming language
Table of Contents
Problem Statement
Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: The correct ordering being: Note:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Order by pair comparisons step by step in the Action! programming language
Source code in the action! programming language
DEFINE PTR="CARD"
PROC PrintArray(PTR ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
Print(a(i))
OD
Put(']) PutE()
RETURN
BYTE FUNC IsBefore(CHAR ARRAY a,b)
DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE k
PrintF("Is %S before %S (y/n)? ",a,b)
CH=NO_KEY ;Flush the keyboard
DO
k=CH
UNTIL k=KEY_Y OR k=KEY_N
OD
CH=NO_KEY ;Flush the keyboard
IF k=KEY_Y THEN
PrintE("yes")
RETURN (1)
FI
PrintE("no")
RETURN (0)
PROC InteractiveInsertionSort(PTR ARRAY a BYTE size)
INT i,j
PTR value
FOR i=1 TO size-1
DO
value=a(i)
j=i-1
WHILE j>=0 AND IsBefore(value,a(j))=1
DO
a(j+1)=a(j)
j==-1
OD
a(j+1)=value
OD
RETURN
PROC Main()
DEFINE COUNT="7"
PTR ARRAY arr(COUNT)
arr(0)="violet" arr(1)="red"
arr(2)="green" arr(3)="indigo"
arr(4)="blue" arr(5)="yellow"
arr(6)="orange"
Print("Shuffled array: ")
PrintArray(arr,COUNT) PutE()
InteractiveInsertionSort(arr,COUNT)
PutE() Print("Sorted array: ")
PrintArray(arr,COUNT)
RETURN
You may also check:How to resolve the algorithm Animation step by step in the Fantom programming language
You may also check:How to resolve the algorithm Mad Libs step by step in the Applesoft BASIC programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the COBOL programming language
You may also check:How to resolve the algorithm URL decoding step by step in the C++ programming language
You may also check:How to resolve the algorithm Polyspiral step by step in the Python programming language