How to resolve the algorithm Order by pair comparisons step by step in the XPL0 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Order by pair comparisons step by step in the XPL0 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 XPL0 programming language
Source code in the xpl0 programming language
include xpllib; \for Print
int Items, Size, I, J, Gap, JG, T, C, Count;
[Items:= ["violet", "red", "green", "indigo", "blue", "yellow", "orange"];
Size:= 7;
Count:= 0;
Gap:= Size>>1;
while Gap > 0 do
[for I:= Gap to Size-1 do
[J:= I - Gap;
loop [JG:= J + Gap;
Count:= Count+1;
Print("%2d: Is %6s less than %6s (y/n)? ",
Count, Items(J), Items(JG));
repeat OpenI(1);
C:= ChIn(1);
until C=^y or C=^n;
ChOut(0, C); CrLf(0);
if C = ^y then quit;
T:= Items(J); Items(J):= Items(JG); Items(JG):= T;
J:= J - Gap;
if J < 0 then quit;
];
];
Gap:= Gap>>1;
];
Print("The colors of the rainbow, in sorted order, are:\n");
for I:= 0 to Size-2 do Print("%s, ", Items(I));
Print("%s\n", Items(I));
]
You may also check:How to resolve the algorithm Dutch national flag problem step by step in the Logo programming language
You may also check:How to resolve the algorithm Detect division by zero step by step in the C# programming language
You may also check:How to resolve the algorithm Emirp primes step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the Action! programming language
You may also check:How to resolve the algorithm Delete a file step by step in the Seed7 programming language