How to resolve the algorithm Sort an array of composite structures step by step in the Erlang 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 Erlang 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 Erlang programming language
Source code in the erlang programming language
1> lists:sort([{{2006,2007},"Ducks"},
{{2000,2001},"Avalanche"},
{{2002,2003},"Devils"},
{{2001,2002},"Red Wings"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2005,2006},"Hurricanes"},
{{1999,2000},"Devils"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}]).
[{{1999,2000},"Devils"},
{{2000,2001},"Avalanche"},
{{2001,2002},"Red Wings"},
{{2002,2003},"Devils"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2005,2006},"Hurricanes"},
{{2006,2007},"Ducks"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}]
2> F = fun({_,X},{_,Y}) -> X < Y end.
#Fun<erl_eval.12.113037538>
3> lists:usort(F, [{{2006,2007},"Ducks"},
{{2000,2001},"Avalanche"},
{{2002,2003},"Devils"},
{{2001,2002},"Red Wings"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2005,2006},"Hurricanes"},
{{1999,2000},"Devils"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}]).
[{{2000,2001},"Avalanche"},
{{1999,2000},"Devils"},
{{2002,2003},"Devils"},
{{2006,2007},"Ducks"},
{{2005,2006},"Hurricanes"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2008,2009},"Penguins"},
{{2007,2008},"Red Wings"},
{{2001,2002},"Red Wings"}]
You may also check:How to resolve the algorithm Sum and product of an array step by step in the PHP programming language
You may also check:How to resolve the algorithm Order disjoint list items step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sorting algorithms/Comb sort step by step in the Oz programming language
You may also check:How to resolve the algorithm Euler's sum of powers conjecture step by step in the BASIC programming language
You may also check:How to resolve the algorithm Sutherland-Hodgman polygon clipping step by step in the Swift programming language