Sort an array of composite structures: Difference between revisions

m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(24 intermediate revisions by 15 users not shown)
Line 1:
{{task|Sorting Algorithms}}
{{Sorting Algorithm}}
[[Category:Sorting]]
{{task|Sorting}}
 
Sort an array of composite structures by a key.
Line 14:
and an array of such pairs:
 
x: array of 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.
 
If your language is not listed here, please see the other article.
<br><br>
=={{header|11l}}==
{{trans|Kotlin}}
 
<syntaxhighlight lang="11l">T Employee
String name, category
 
F (name, category)
.name = name
.category = category
 
V employees = [
Employee(‘David’, ‘Manager’),
Employee(‘Alice’, ‘Sales’),
Employee(‘Joanna’, ‘Director’),
Employee(‘Henry’, ‘Admin’),
Employee(‘Tim’, ‘Sales’),
Employee(‘Juan’, ‘Admin’)
]
 
employees.sort(key' e -> e.name)
 
L(e) employees
print(‘#<6 : #.’.format(e.name, e.category))</syntaxhighlight>
 
{{out}}
<pre>
Alice : Sales
David : Manager
Henry : Admin
Joanna : Director
Juan : Admin
Tim : Sales
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program shellSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*******************************************/
/* Structures */
/********************************************/
/* city structure */
.struct 0
city_name: //
.struct city_name + 8 // string pointer
city_habitants: //
.struct city_habitants + 8 // integer
city_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Name : @ number habitants : @ \n"
szMessSortHab: .asciz "Sort table for number of habitants :\n"
szMessSortName: .asciz "Sort table for name of city :\n"
szCarriageReturn: .asciz "\n"
 
// cities name
szCeret: .asciz "Ceret"
szMaureillas: .asciz "Maureillas"
szTaillet: .asciz "Taillet"
szReynes: .asciz "Reynes"
szVives: .asciz "Vivés"
szBoulou: .asciz "Le Boulou"
szSaintJean: .asciz "Saint Jean Pla de Corts"
szCluses: .asciz "Les Cluses"
szAlbere: .asciz "L'Albère"
szPerthus: .asciz "Le Perthus"
 
.align 4
TableCities:
.quad szCluses // address name string
.quad 251 // number of habitants
.quad szCeret
.quad 7705
.quad szMaureillas
.quad 2596
.quad szBoulou
.quad 5554
.quad szSaintJean
.quad 2153
.quad szAlbere
.quad 83
.quad szVives
.quad 174
.quad szTaillet
.quad 115
.quad szPerthus
.quad 586
.quad szReynes
.quad 1354
.equ NBELEMENTS, (. - TableCities) / city_end
.skip city_end // temp area for element in shellSort
// see other soluce to use stack
// in programm arm assembly in this forum
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessSortHab
bl affichageMess
 
ldr x0,qAdrTableCities // address table
mov x1,0 // not use in routine
mov x2,NBELEMENTS // number of élements
mov x3,#city_habitants // sort by number habitants
mov x4,#'N' // numeric
bl shellSort
ldr x0,qAdrTableCities // address table
bl displayTable
ldr x0,qAdrszMessSortName
bl affichageMess
 
ldr x0,qAdrTableCities // address table
mov x1,0 // not use in routine
mov x2,NBELEMENTS // number of élements
mov x3,#city_name // sort by city name
mov x4,#'A' // alphanumeric
bl shellSort
ldr x0,qAdrTableCities // address table
bl displayTable
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableCities: .quad TableCities
qAdrszMessSortHab: .quad szMessSortHab
qAdrszMessSortName: .quad szMessSortName
/***************************************************/
/* shell Sort */
/***************************************************/
/* x0 contains the address of table */
/* x1 contains the first element but not use !! */
/* this routine use first element at index zero !!! */
/* x2 contains the number of element */
/* x3 contains the offset of sort zone */
/* x4 contains type of sort zone N = numeric A = alphanumeric */
shellSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
stp x12,x13,[sp,-16]! // save registers
mov x8,x3 // save offset area sort
mov x9,x4 // save type sort
mov x7,city_end // element size
sub x12,x2,1 // index last item
mov x11,x12 // init gap = last item
1: // start loop 1
lsr x11,x11,1 // gap = gap / 2
cbz x11,100f // if gap = 0 -> end
mov x3,x11 // init loop indice 1
2: // start loop 2
mul x1,x3,x7 // offset élement
mov x2,NBELEMENTS
mul x2,x7,x2
bl copyElement
add x1,x1,x8 // + offset sort zone
ldr x4,[x0,x1] // load first value
mov x5,x3 // init loop indice 2
3: // start loop 3
cmp x5,x11 // indice < gap
blt 7f // yes -> end loop 2
sub x6,x5,x11 // index = indice - gap
mul x1,x6,x7 // compute offset
add x10,x1,x8 // + offset sort zone
ldr x2,[x0,x10] // load second value
cmp x9,#'A' // sort area alapha ?
beq 4f // yes
cmp x4,x2 // else compare numeric values
bge 7f // highter
b 6f // lower
4: // compare area alphanumeric
mov x10,#0 // counter
5:
ldrb w13,[x4,x10] // byte string 1
ldrb w6,[x2,x10] // byte string 2
cmp w13,w6
bgt 7f
blt 6f
 
cmp w13,#0 // end string 1
beq 7f // end comparaison
add x10,x10,#1 // else add 1 in counter
b 5b // and loop
 
6:
mul x2,x5,x7 // offset élement
bl copyElement // copy element x1 to element x2
sub x5,x5,x11 // indice = indice - gap
b 3b // and loop
7:
mov x1,NBELEMENTS
mul x1,x7,x1
mul x2,x7,x5
bl copyElement
add x3,x3,1 // increment indice 1
cmp x3,x12 // end ?
ble 2b // no -> loop 2
b 1b // yes loop for new gap
100: // end function
ldp x12,x13,[sp],16 // restaur 2 registers
ldp x10,x11,[sp],16 // restaur 2 registers
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
 
/******************************************************************/
/* copy table element */
/******************************************************************/
/* r0 contains the address of table */
/* r1 offset origin element */
/* r2 offset destination element */
copyElement:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,0
add x1,x1,x0
add x2,x2,x0
1:
ldrb w4,[x1,x3]
strb w4,[x2,x3]
add x3,x3,1
cmp x3,city_end
blt 1b
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
mov x6,city_end
1: // loop display table
mul x4,x3,x6
add x4,x4,city_name
ldr x1,[x2,x4]
ldr x0,qAdrsMessResult
bl strInsertAtCharInc // put name in message
mov x5,x0 // save address of new message
mul x4,x3,x6
add x4,x4,city_habitants // and load value
ldr x0,[x2,x4]
ldr x1,qAdrsZoneConv // display value
bl conversion10 // call function
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,#NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Sort table for number of habitants :
Name : L'Albère number habitants : 83
Name : Taillet number habitants : 115
Name : Vivés number habitants : 174
Name : Les Cluses number habitants : 251
Name : Le Perthus number habitants : 586
Name : Reynes number habitants : 1354
Name : Saint Jean Pla de Corts number habitants : 2153
Name : Maureillas number habitants : 2596
Name : Le Boulou number habitants : 5554
Name : Ceret number habitants : 7705
 
Sort table for name of city :
Name : Ceret number habitants : 7705
Name : L'Albère number habitants : 83
Name : Le Boulou number habitants : 5554
Name : Le Perthus number habitants : 586
Name : Les Cluses number habitants : 251
Name : Maureillas number habitants : 2596
Name : Reynes number habitants : 1354
Name : Saint Jean Pla de Corts number habitants : 2153
Name : Taillet number habitants : 115
Name : Vivés number habitants : 174
</pre>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun insert-by-key (o os key)
(cond ((endp os) (list o))
((< (cdr (assoc key o))
Line 53 ⟶ 385:
(weight . 15)
(value . 60)))
'value)</langsyntaxhighlight>
 
Output:
Line 71 ⟶ 403:
(WEIGHT . 153)
(VALUE . 200)))</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_an_array_of_composite_structures.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[(Warsaw,Poland) (Prague,Czech Republic) (London,United Kingdom) (Paris,France) (Madrit,Spain) (Berlin,Germany) (Rome,Italy) (Moscow,Russia) (Budapest,Hungary)]
 
Array after sort:
[(Berlin,Germany) (Budapest,Hungary) (London,United Kingdom) (Madrit,Spain) (Moscow,Russia) (Paris,France) (Prague,Czech Republic) (Rome,Italy) (Warsaw,Poland)]
</pre>
 
=={{header|Ada}}==
[[Ada 2005]] defines 2 standard subprograms for sorting arrays - 1 for constrained arrays and 1 for unconstrained arrays. Below is a example of using the unconstrained version.
<langsyntaxhighlight lang="ada">with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 114 ⟶ 542:
Put_Line (Data (I));
end loop;
end Demo_Array_Sort;</langsyntaxhighlight>
Result:
<pre>
Line 125 ⟶ 553:
</pre>
[[Ada 2005]] also provides ordered containers, so no explicit call is required. Here is an example of an ordered set:
<langsyntaxhighlight lang="ada">with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 166 ⟶ 594:
Data.Insert (New_Item => (Name => +"David", Value => +"19"));
Data.Iterate (Put_Line'Access);
end Sort_Composites;</langsyntaxhighlight>
Result:
<pre>
Line 177 ⟶ 605:
</pre>
There is no standard sort function for [[Ada 95]]. The example below implements a simple bubble sort.
<langsyntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
 
Line 230 ⟶ 658:
Sort_Name(My_Pairs);
Print(My_Pairs);
end Sort_Composite;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 238 ⟶ 666:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput}} -->
<langsyntaxhighlight lang="algol68">MODE SORTSTRUCT = PERSON;
OP < = (PERSON a,b)BOOL: age OF a < age OF b;
PR READ "prelude/sort.a68" PR;
Line 246 ⟶ 674:
 
[]SORTSTRUCT person = (("joe", 120), ("foo", 31), ("bar", 51));
printf((person repr, shell sort(person), $l$))</langsyntaxhighlight>
Output:
<pre>
Line 257 ⟶ 685:
macOS Yosemite onwards, for import of Foundation framework
 
<langsyntaxhighlight AppleScriptlang="applescript">use framework "Foundation"
 
----- SORTING COMPOSITE STRUCTURES (BY MULTIPLE KEYS) ------
Line 328 ⟶ 756:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{{pop:24.2, city:"Sao Paulo "}, {pop:24.2, city:"Shanghai "}, {pop:23.5, city:"Karachi "}, {pop:21.5, city:"Beijing "}, {pop:17.0, city:"Dhaka "}, {pop:16.8, city:"Delhi "}, {pop:16.1, city:"Lagos "}}</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
=={{header|Arturo}}==
/* program compositeSort.s */
 
/* REMARK 1 : this program use routines in a include file
<lang arturo>arr: #(#{ name: "Joe" , value: 3 };
see task Include a file language arm assembly
#{ name: "Bill" , value: 4 };
for the routine affichageMess conversion10
#{ name: "Alice" , value: 20 };
see at end of this program the instruction include */
#{ name: "Harry" , value: 3 })
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
 
/*******************************************/
sortBy! arr -> &.value
/* Structures */
/********************************************/
/* city structure */
.struct 0
city_name: @
.struct city_name + 4
city_habitants: @
.struct city_habitants + 4
city_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Name : @ number habitants : @ \n"
szMessSortHab: .asciz "Sort table for number of habitants :\n"
szMessSortName: .asciz "Sort table for name of city :\n"
szCarriageReturn: .asciz "\n"
// cities name
szCeret: .asciz "Ceret"
szMaureillas: .asciz "Maureillas"
szTaillet: .asciz "Taillet"
szReynes: .asciz "Reynes"
szVives: .asciz "Vivés"
szBoulou: .asciz "Le Boulou"
szSaintJean: .asciz "Saint Jean Pla de Corts"
szCluses: .asciz "Les Cluses"
szAlbere: .asciz "L'Albère"
szPerthus: .asciz "Le Perthus"
.align 4
 
TableCities:
print arr</lang>
.int szCluses @ address name string
.int 251 @ number of habitants
.int szCeret
.int 7705
.int szMaureillas
.int 2596
.int szBoulou
.int 5554
.int szSaintJean
.int 2153
.int szAlbere
.int 83
.int szVives
.int 174
.int szTaillet
.int 115
.int szPerthus
.int 586
.int szReynes
.int 1354
.equ NBELEMENTS, (. - TableCities) / city_end
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessSortHab
bl affichageMess
 
ldr r0,iAdrTableCities @ address city table
mov r1,#0 @ not use in routine
mov r2,#NBELEMENTS @ number of élements
mov r3,#city_habitants @ sort by number habitants
mov r4,#'N' @ Alphanumeric
bl shellSort
ldr r0,iAdrTableCities @ address number table
bl displayTable
ldr r0,iAdrszMessSortName
bl affichageMess
ldr r0,iAdrTableCities @ address city table
mov r1,#0 @ not use in routine
mov r2,#NBELEMENTS @ number of élements
mov r3,#city_name @ sort by name
mov r4,#'A' @ Alphanumeric
bl shellSort
ldr r0,iAdrTableCities @ address number table
bl displayTable
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableCities: .int TableCities
iAdrszMessSortHab: .int szMessSortHab
iAdrszMessSortName: .int szMessSortName
/***************************************************/
/* shell Sort */
/***************************************************/
 
/* r0 contains the address of table */
/* r1 contains the first element but not use !! */
/* this routine use first element at index zero !!! */
/* r2 contains the number of element */
/* r3 contains the offset of sort zone */
/* r4 contains type of sort zone N = numeric A = alphanumeric */
shellSort:
push {r0-r12,lr} @ save registers
sub sp,#city_end @ reserve area on stack
mov fp,sp @ frame pointer = stack
mov r8,r3 @ save offser area sort
mov r9,r4 @ save type sort
mov r7,#city_end @ element size
//vidregtit debut
sub r12,r2,#1 @ index last item
mov r6,r12 @ init gap = last item
1: @ start loop 1
lsrs r6,#1 @ gap = gap / 2
beq 100f @ if gap = 0 -> end
mov r3,r6 @ init loop indice 1
2: @ start loop 2
mul r1,r3,r7 @ offset élement
mov r2,fp @ save on stack
bl saveElement
add r1,r8 @ + offset sort zone
ldr r4,[r0,r1] @ load first value
mov r5,r3 @ init loop indice 2
3: @ start loop 3
cmp r5,r6 @ indice < gap
blt 8f @ yes -> end loop 2
sub r10,r5,r6 @ index = indice - gap
mul r1,r10,r7 @ offset élement
add r10,r1,r8 @ + offset sort zone
ldr r2,[r0,r10] @ load second value
push {r3,r5} @ save registrars because not enought register
cmp r9,#'A' @ sort area alapha ?
beq 4f @ yes
cmp r4,r2 @ else compare numeric values
bge 7f @ highter
b 6f @ lower
4: @ compare area alphanumeric
mov r10,#0 @ counter
5:
ldrb r3,[r4,r10] @ byte string 1
ldrb r5,[r2,r10] @ byte string 2
cmp r3,r5
bgt 7f
blt 6f
 
cmp r3,#0 @ end string 1
beq 7f @ ens comparaison
add r10,r10,#1 @ else add 1 in counter
b 5b @ and loop
6:
pop {r3,r5} @ restaur registers
mul r2,r5,r7 @ offset élement
bl copyElement @ copy element r1 to element r2
sub r5,r6 @ indice = indice - gap
b 3b @ and loop
7:
pop {r3,r5}
8: @ end loop 3
mul r1,r5,r7 @ offset destination élement
mov r2,fp @ restaur element in table
bl restaurElement
add r3,#1 @ increment indice 1
cmp r3,r12 @ end ?
ble 2b @ no -> loop 2
b 1b @ yes loop for new gap
100: @ end function
add sp,#city_end
pop {r0-r12,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* copy table element */
/******************************************************************/
/* r0 contains the address of table */
/* r1 offset origin element */
/* r2 offset destination element */
copyElement:
push {r0-r4,lr} @ save registers
//vidregtit copy
mov r3,#0
add r1,r0
add r2,r0
1:
ldrb r4,[r1,r3]
strb r4,[r2,r3]
add r3,#1
cmp r3,#city_end
blt 1b
100:
pop {r0-r4,lr}
bx lr
/******************************************************************/
/* save element */
/******************************************************************/
/* r0 contains the address of table */
/* r1 offset origin element */
/* r2 address destination */
saveElement:
push {r0-r4,lr} @ save registers
mov r3,#0
add r1,r0
1:
ldrb r4,[r1,r3]
strb r4,[r2,r3]
add r3,#1
cmp r3,#city_end
blt 1b
100:
pop {r0-r4,lr}
bx lr
/******************************************************************/
/* restaur element */
/******************************************************************/
/* r0 contains the address of table */
/* r1 offset destination element */
/* r2 address origine */
restaurElement:
push {r0-r4,lr} @ save registers
mov r3,#0
add r1,r0
1:
ldrb r4,[r2,r3]
strb r4,[r1,r3]
add r3,#1
cmp r3,#city_end
blt 1b
100:
pop {r0-r4,lr}
bx lr
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r6,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
mov r6,#city_end
1: @ loop display table
mul r4,r3,r6
add r4,#city_name
ldr r1,[r2,r4]
ldr r0,iAdrsMessResult
bl strInsertAtCharInc @ put name in message
mov r5,r0 @ save address of new message
mul r4,r3,r6
add r4,#city_habitants @ and load value
ldr r0,[r2,r4]
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
mov r0,r5
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r6,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
Sort table for number of habitants :
Name : L'Albère number habitants : 83
Name : Taillet number habitants : 115
Name : Vivés number habitants : 174
Name : Les Cluses number habitants : 251
Name : Le Perthus number habitants : 586
Name : Reynes number habitants : 1354
Name : Saint Jean Pla de Corts number habitants : 2153
Name : Maureillas number habitants : 2596
Name : Le Boulou number habitants : 5554
Name : Ceret number habitants : 7705
 
Sort table for name of city :
Name : Ceret number habitants : 7705
Name : L'Albère number habitants : 83
Name : Le Boulou number habitants : 5554
Name : Le Perthus number habitants : 586
Name : Les Cluses number habitants : 251
Name : Maureillas number habitants : 2596
Name : Reynes number habitants : 1354
Name : Saint Jean Pla de Corts number habitants : 2153
Name : Taillet number habitants : 115
Name : Vivés number habitants : 174
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">people: [
["joe" 120]
["foo" 31]
["bar" 51]
]
 
print arrange people 'x -> x\0</syntaxhighlight>
 
{{out}}
 
<pre>[bar 51] [foo 31] [joe 120]</pre>
<pre>#(#{ name: "Joe", value: 3 } #{ name: "Harry", value: 3 } #{ name: "Bill", value: 4 } #{ name: "Alice", value: 20 })</pre>
 
=={{header|ATS}}==
 
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats"
 
typedef pair =
'{
name = string,
value = string
}
 
fn
sort_pairs {n : int}
(pairs : &array (pair, n) >> _,
n : size_t n)
:<!wrt> void =
let
implement
array_quicksort$cmp<pair> (x, y) =
strcmp (x.name, y.name)
in
array_quicksort<pair> (pairs, n)
end
 
implement
main0 () =
let
val pairs_list : list (pair, 9) =
$list
('{name = "Warsaw", value = "Poland"},
'{name = "Prague", value = "Czech Republic"},
'{name = "London", value = "United Kingdom"},
'{name = "Paris", value = "France"},
'{name = "Madrid", value = "Spain"},
'{name = "Berlin", value = "Germany"},
'{name = "Rome", value = "Italy"},
'{name = "Moscow", value = "Russia"},
'{name = "Budapest", value = "Hungary"})
 
var pairs_array : @[pair][9]
val () = array_initize_list<pair> (pairs_array, 9, pairs_list)
 
val () = sort_pairs (pairs_array, i2sz 9)
 
var i : [i : nat | i <= 9] int i
in
for (i := 0; i <> 9; i := succ i)
println! (pairs_array[i].name, " -> ", pairs_array[i].value)
end</syntaxhighlight>
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW -O3 sort_composite_structures.dats -lgc && ./a.out
Berlin -> Germany
Budapest -> Hungary
London -> United Kingdom
Madrid -> Spain
Moscow -> Russia
Paris -> France
Prague -> Czech Republic
Rome -> Italy
Warsaw -> Poland</pre>
 
=={{header|AutoHotkey}}==
built ListView Gui, contains a table sorting function which can be used for this.
<langsyntaxhighlight AutoHotkeylang="autohotkey">start:
Gui, Add, ListView, r20 w200, 1|2
data =
Line 372 ⟶ 1,178:
 
GuiClose:
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SORT_AN_ARRAY_OF_COMPOSITE_STRUCTURES.AWK
BEGIN {
Line 410 ⟶ 1,216:
printf("\n")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 421 ⟶ 1,227:
First, we construct a list-of-maps and assign it to variable baz. Next, we sort baz by key "foo" and assign it to variable bop. Finally, we lookup "foo" in each map in list bop and display the resulting list of numbers - they are in sorted order.
 
<langsyntaxhighlight lang="babel">babel> baz ([map "foo" 3 "bar" 17] [map "foo" 4 "bar" 18] [map "foo" 5 "bar" 19] [map "foo" 0 "bar" 20]) <
babel> bop baz { <- "foo" lumap ! -> "foo" lumap ! lt? } lssort ! <
babel> bop {"foo" lumap !} over ! lsnum !
( 0 3 4 5 )</langsyntaxhighlight>
 
The same technique works for any list of data-objects you may have. User-code can expect to have the top two elements of the stack set to be the two objects to be compared. Simply access the relevant field in each object, and then perform a comparison. For example, here is a list of pairs sorted by first element:
 
<langsyntaxhighlight lang="babel">babel> 20 lsrange ! {1 randlf 2 rem} lssort ! 2 group ! --> this creates a shuffled list of pairs
babel> dup {lsnum !} ... --> display the shuffled list, pair-by-pair
( 11 10 )
Line 451 ⟶ 1,257:
( 15 13 )
( 17 3 )
( 18 9 )</langsyntaxhighlight>
 
The gpsort utility performs this kind of comparison "automagically" by leveraging the ordering of Babel's underlying data-structure. Using the shuffled list from the example above:
 
<langsyntaxhighlight lang="babel">babel> gpsort !
babel> dup {lsnum !} ...
( 0 2 )
Line 466 ⟶ 1,272:
( 15 13 )
( 17 3 )
( 18 9 )</langsyntaxhighlight>
 
Note that gpsort will not work for the case where you want to sort on the second element of a list of pairs. But it will work for performing a canonical sort on numbers, arrays of numbers, lists of numbers, lists of lists, lists of arrays, arrays of lists, and so on. You should not use gpsort with strings; use lexsort or strsort instead. Here's an example of sorting a mixture of pairs and triples using gpsort:
 
<langsyntaxhighlight lang="babel">babel> dup {lsnum !} ... --> display the shuffled list of pairs and triples
( 7 2 )
( 6 4 )
Line 492 ⟶ 1,298:
( 8 2 3 )
( 9 6 10 )
( 11 13 7 )</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Uses the supplied SORTSALIB library.
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTSALIB"
sort% = FN_sortSAinit(0,0)
Line 515 ⟶ 1,321:
FOR i% = 1 TO DIM(array{()}, 1)
PRINT array{(i%)}.name$, array{(i%)}.number%
NEXT</langsyntaxhighlight>
Output:
<pre>
Line 532 ⟶ 1,338:
=={{header|Bracmat}}==
The easiest way to sort an array of elements in Bracmat is to handle it as a sum of terms. A sum, when evaluated, is automatically sorted.
<langsyntaxhighlight lang="bracmat">( (tab=("C++",1979)+(Ada,1983)+(Ruby,1995)+(Eiffel,1985))
& out$"unsorted array:"
& lst$tab
Line 538 ⟶ 1,344:
& out$"But tab is still unsorted:"
& lst$tab
);</langsyntaxhighlight>
 
Output:
Line 555 ⟶ 1,361:
 
When evaluating <code>!tab</code>, the expression bound to the variable name <code>tab</code> is sorted, but the unevaluated expression is still bound to <code>tab</code>. An assignment binds the sorted expression to <code>tab</code>:
<langsyntaxhighlight lang="bracmat">( !tab:?tab
& out$"Now tab is sorted:"
& lst$tab
);</langsyntaxhighlight>
 
Output:
Line 567 ⟶ 1,373:
 
To sort an array that is not a sum expression, we can convert it to a sum:
<langsyntaxhighlight lang="bracmat">( ((name.map),(weight.9),(value.150))
((name.compass),(weight.13),(value.35))
((name.water),(weight.153),(value.200))
Line 587 ⟶ 1,393:
& out$("Array after sorting (descending order):" !array \n)
& out$("Array after sorting (ascending order):" reverse$!array \n)
);</langsyntaxhighlight>
 
Output:
Line 614 ⟶ 1,420:
 
Bracmat has a left to right sorting order. If an array must be sorted on another field than the first field, that other field has to be made the first field. After sorting, the fields can take their original positions.
<langsyntaxhighlight lang="bracmat">( (Joe,5531)
(Adam,2341)
(Bernie,122)
Line 635 ⟶ 1,441:
\n
)
);</langsyntaxhighlight>
 
Output:
Line 655 ⟶ 1,461:
=={{header|C}}==
Using qsort, from the standard library.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 752 ⟶ 1,558:
 
return 0;
}</langsyntaxhighlight>
Output:
<pre> This is the order in which many strings should be sorted.
Line 760 ⟶ 1,566:
{{works with|C sharp|C#|3+}}
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 786 ⟶ 1,592:
Console.WriteLine("{0,-11}{1}", e.Name, e.Value);
}
}</langsyntaxhighlight>
 
Output:
Line 800 ⟶ 1,606:
Uses C++11. Compile with
g++ -std=c++11 sort.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <string>
Line 827 ⟶ 1,633:
std::cout << "{" << e.name << ", " << e.value << "}\n";
}
}</langsyntaxhighlight>
Output:
<pre>
Line 845 ⟶ 1,651:
Clojure has a ''sort-by'' function which takes a ''keyfn'' and a ''coll''. It returns a sorted sequence of the items in ''coll'', where the sort order is determined by comparing ''(keyfn item)''.
 
<langsyntaxhighlight lang="clojure">
;; Gathered with Google Squared
(def *langs* [["Clojure" 2007] ["Common Lisp" 1984] ["Java" 1995] ["Haskell" 1990]
Line 853 ⟶ 1,659:
 
(["Lisp" 1958] ["Scheme" 1975] ["Common Lisp" 1984] ["Haskell" 1990] ["Java" 1995] ["Clojure" 2007])
</syntaxhighlight>
</lang>
 
You can also supply a comparator (using ''compare'' or a sibling of ''<''). A comparator can be used with the regular ''sort'' function or the ''sort-by'' function. In the latter case, the comparator will be used on ''(keyfn item)'' instead of ''item''.
 
<langsyntaxhighlight lang="clojure">
user> (sort #(compare (second %1) (second %2)) *langs*) ; using a comparator
 
Line 865 ⟶ 1,671:
 
(["Clojure" 2007] ["Java" 1995] ["Haskell" 1990] ["Common Lisp" 1984] ["Scheme" 1975] ["Lisp" 1958])
</syntaxhighlight>
</lang>
 
Read the docstring of ''sort'' and ''sort-by'' for more info.
Line 874 ⟶ 1,680:
Let's define a composite structure of U.S. states and average test scores.
 
<langsyntaxhighlight lang="lisp">CL-USER> (defparameter *test-scores* '(("texas" 68.9) ("ohio" 87.8) ("california" 76.2) ("new york" 88.2)) )
*TEST-SCORES*</langsyntaxhighlight>
We can sort by the state name by supplying a one-argument key function that is called by the ''sort'' function to determine the value to compare. In this case, the function is ''first'' will retrieve the state name:
 
<langsyntaxhighlight lang="lisp">CL-USER> (sort (copy-list *test-scores*) #'string-lessp :key #'first)
(("california" 76.2) ("new york" 88.2) ("ohio" 87.8) ("texas" 68.9))</langsyntaxhighlight>
 
we can also sort by the test scores by supplying a different key function that return the test score instead:
 
<langsyntaxhighlight lang="lisp">CL-USER> (sort (copy-list *test-scores*) #'< :key #'second)
(("texas" 68.9) ("california" 76.2) ("ohio" 87.8) ("new york" 88.2))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
struct Pair { string name, value; }
Line 900 ⟶ 1,706:
 
pairs.schwartzSort!q{ a.name }.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[Pair("Adam", "2341"), Pair("Bernie", "122"), Pair("David", "19"), Pair("Joe", "5531"), Pair("Walter", "1234")]</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program SortCompositeStructures;
 
{$APPTYPE CONSOLE}
Line 937 ⟶ 1,743:
Result := CompareText(Left.Name, Right.Name);
end));
end.</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def compareBy(keyfn) { # This ought to be in the standard library
return def comparer(a, b) {
return keyfn(a).op__cmp(keyfn(b))
Line 954 ⟶ 1,760:
]
 
println(x.sort(compareBy(fn [name,_] { name })))</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; sorting (name value) by name - Ignoring case
(define (name a) (first a))
Line 969 ⟶ 1,775:
→ (("albert" 33) ("Antoinette" 42) ("elvis" 666) ("Simone" 44) ("😃" 1000) ("😎" -42))
 
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 986 ⟶ 1,792:
KeyValue.new("Germanium", 72.64r)};
var sorted := elements.sort::(former,later => former.Key < later.Key );
sorted.forEach::(element)
{
console.printLine(element.Key," - ",element)
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Person do
defstruct name: "", value: 0
end
Line 1,006 ⟶ 1,812:
Enum.sort(list) |> Enum.each(fn x -> IO.inspect x end)
IO.puts ""
Enum.sort_by(list, &(&1.value)) |> Enum.each(&IO.inspect &1)</langsyntaxhighlight>
 
{{out}}
Line 1,023 ⟶ 1,829:
=={{header|Erlang}}==
Any Erlang type can be compared to any Erlang type. As such, nothing special needs to be done:
<langsyntaxhighlight Erlanglang="erlang">1> lists:sort([{{2006,2007},"Ducks"},
{{2000,2001},"Avalanche"},
{{2002,2003},"Devils"},
Line 1,042 ⟶ 1,848:
{{2006,2007},"Ducks"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}]</langsyntaxhighlight>
 
It is also possible to sort with custom functions, in this case by the team's name:
<langsyntaxhighlight Erlanglang="erlang">2> F = fun({_,X},{_,Y}) -> X < Y end.
#Fun<erl_eval.12.113037538>
3> lists:usort(F, [{{2006,2007},"Ducks"},
Line 1,066 ⟶ 1,872:
{{2008,2009},"Penguins"},
{{2007,2008},"Red Wings"},
{{2001,2002},"Red Wings"}]</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include sort.e
include misc.e
 
Line 1,083 ⟶ 1,889:
{ "cherry", "red" } }
 
pretty_print(1,custom_sort(routine_id("compare_names"),s),{2})</langsyntaxhighlight>
 
Output:
Line 1,107 ⟶ 1,913:
=={{header|F_Sharp|F#}}==
F# has <code>sortBy</code> functions that work on collection types for this purpose. An example using an array of pairs:
<langsyntaxhighlight lang="fsharp">let persons = [| ("Joe", 120); ("foo", 31); ("bar", 51) |]
Array.sortInPlaceBy fst persons
printfn "%A" persons</langsyntaxhighlight>
Output:
Line 1,115 ⟶ 1,921:
 
An example using a list of records:
<langsyntaxhighlight lang="fsharp">type Person = { name:string; id:int }
let persons2 = [{name="Joe"; id=120}; {name="foo"; id=31}; {name="bar"; id=51}]
let sorted = List.sortBy (fun p -> p.id) persons2
for p in sorted do printfn "%A" p</langsyntaxhighlight>
 
Output:
Line 1,131 ⟶ 1,937:
This is essentially the same as [[Sorting Using a Custom Comparator]].
 
<langsyntaxhighlight lang="factor">TUPLE: example-pair name value ;
 
: sort-by-name ( seq -- seq' ) [ [ name>> ] compare ] sort ;</langsyntaxhighlight>
 
( scratchpad ) { T{ example-pair f "omega" "a" } T{ example-pair f "gamma" "q" } T{ example-pair f "alpha" "z" } } sort-by-name .
Line 1,146 ⟶ 1,952:
Any object can be sorted as needed by passing an appropriate block to the 'sort' method.
 
<langsyntaxhighlight lang="fantom">
class Pair // create a composite structure
{
Line 1,179 ⟶ 1,985:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Standard Fortran has no built-in sort function although some compilers add them. The following example uses an insertion sort.
<langsyntaxhighlight lang="fortran">PROGRAM EXAMPLE
IMPLICIT NONE
 
Line 1,218 ⟶ 2,024:
WRITE (*,"(2A6)") rcc
 
END PROGRAM EXAMPLE</langsyntaxhighlight>
Output
Black 0
Line 1,232 ⟶ 2,038:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Pair
Line 1,284 ⟶ 2,090:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,300 ⟶ 2,106:
[snow, white]
</pre>
 
=={{header|Frink}}==
Frink's <CODE>lexicalCompare[a, b, language]</CODE> function can sort strings in a lexicographically correct way for many human languages by specifying a language specifier like "da" for Danish. This allows sort routines to magically work correctly for many human languages.
<syntaxhighlight lang="frink">class Pair
{
var name
var value
new[name is string, value is string] :=
{
this.name = name
this.value = value
}
}
 
a = [new Pair["one", "1"], new Pair["two", "2"], new Pair["three", "3"]]
sort[a, {|a,b| lexicalCompare[a.name, b.name]}]
</syntaxhighlight>
 
{{out}}
<pre>[Pair
{
name = one
value = 1
}
, Pair
{
name = three
value = 3
}
, Pair
{
name = two
value = 2
}
]
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_an_array_of_composite_structures}}
 
'''Solution'''
 
In the following example, it is assumed that the key is the first element of each pair.
 
[[File:Fōrmulæ - Sort an array of composite structures 01.png]]
 
[[File:Fōrmulæ - Sort an array of composite structures 02.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,330 ⟶ 2,185:
fmt.Printf("%5s: %s\n", p.name, p.value)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">class Holiday {
def date
def name
Line 1,357 ⟶ 2,212:
 
holidays.sort { x, y -> x.date <=> y.date }
holidays.each { println it }</langsyntaxhighlight>
 
Output:
Line 1,376 ⟶ 2,231:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Data.Function (on)
 
Line 1,401 ⟶ 2,256:
mapM_ print $ sort people
putStrLn []
mapM_ print $ sortBy (on compare pVal) people</langsyntaxhighlight>
 
{{Out}}
Line 1,418 ⟶ 2,273:
To sort a list of triples by the third element, for example:
 
<langsyntaxhighlight lang="haskell">import Data.Ord (comparing)
import Data.List (sortBy)
 
Line 1,429 ⟶ 2,284:
 
main :: IO ()
main = mapM_ print $ sortBy (comparing (\(_, _, y) -> y)) xs</langsyntaxhighlight>
{{Out}}
<pre>("Maurice","Wilkes",1913)
Line 1,440 ⟶ 2,295:
=={{header|Icon}} and {{header|Unicon}}==
The built-in procedure sortf will sort a list by the field in a records.
<langsyntaxhighlight Iconlang="icon">record star(name,HIP)
 
procedure main()
Line 1,451 ⟶ 2,306:
write("Some Orion stars by HIP#")
every write( (x := !sortf(Ori,2)).name, " HIP ",x.HIP)
end</langsyntaxhighlight>
 
Sample output:<pre>Some Orion stars by HIP#
Line 1,462 ⟶ 2,317:
The function<tt> /: </tt>sorts anything (its left argument) based on the keys supplied in its right argument. For example:
 
<langsyntaxhighlight lang="j"> names =: ;: 'Perlis Wilkes Hamming Minsky Wilkinson McCarthy'
values=: ;: 'Alan Maurice Richard Marvin James John'
pairs =: values ,. names
Line 1,478 ⟶ 2,333:
+-------+---------+
|James |Wilkinson|
+-------+---------+</langsyntaxhighlight>
 
Alternatively, J's cross operator will use the same values for both the left and right arguments for /: but, in this case, /:~ is not desirable because that would have us sorting on the values (the first column) and only using the second column for equal names (none of which appear, here).
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.Comparator;
 
Line 1,516 ⟶ 2,371:
});
}
}</langsyntaxhighlight>
Output:
<pre>00-01 Avalanche
Line 1,531 ⟶ 2,386:
In Java 8, we can write the above using a lambda:
{{works with|Java|8+}}
<langsyntaxhighlight lang="java"> public static void sortByName(Pair[] pairs) {
Arrays.sort(pairs, (p1, p2) -> p1.name.compareTo(p2.name));
}</langsyntaxhighlight>
 
We can further use <code>Comparator.comparing()</code> to construct the comparator from a "key" function:
{{works with|Java|8+}}
<langsyntaxhighlight lang="java"> public static void sortByName(Pair[] pairs) {
Arrays.sort(pairs, Comparator.comparing(p -> p.name));
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">var arr = [
{id: 3, value: "foo"},
{id: 2, value: "bar"},
Line 1,551 ⟶ 2,406:
];
arr = arr.sort(function(a, b) {return a.id - b.id}); // Sort with comparator checking the id.
</syntaxhighlight>
</lang>
 
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,616 ⟶ 2,471:
.sort(on(flip(compare), name))
});
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,744 ⟶ 2,599:
=={{header|jq}}==
In this section we will focus on JSON objects since the task description mentions keys. As an example, we will use this array:
<langsyntaxhighlight lang="jq">def example:
[
{"name": "Joe", "value": 3},
Line 1,750 ⟶ 2,605:
{"name": "Alice", "value": 20},
{"name": "Harry", "value": 3}
];</langsyntaxhighlight>
====Using sort_by builtin ====
jq's sort_by builtin can be used to sort by the value of a given key (whether or not it is a string), so we will first use that.
<langsyntaxhighlight lang="jq"># To sort the array:
# example | sort_by(.name)
 
# To abbreviate the results, we will just show the names after sorting:
 
example | sort_by(.name) | map( .name )</langsyntaxhighlight>
{{Out}}
$ jq -n -c -f Sort_an_array_of_composite_structures.jq
Line 1,765 ⟶ 2,620:
====Using quicksort(cmp)====
sort_by(f) can easily be implemented using quicksort(cmp) as defined at [[Sorting_Using_a_Custom_Comparator#jq]] as follows:
<langsyntaxhighlight lang="jq">def quicksort_by(f): quicksort( (.[0]|f) <= (.[1]|f) );</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">example | quicksort_by(.name) | map( .name )</langsyntaxhighlight>
{{Out}}
As above.
Line 1,774 ⟶ 2,629:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">lst = Pair[Pair("gold", "shiny"),
Pair("neon", "inert"),
Pair("sulphur", "yellow"),
Line 1,790 ⟶ 2,645:
println("\nThe list, sorted by name: \n - ", join(lst, "\n - "))
sort!(lst; by=last)
println("\nThe list, sorted by value: \n - ", join(lst, "\n - "))</langsyntaxhighlight>
 
{{out}}
Line 1,833 ⟶ 2,688:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
data class Employee(val name: String, var category: String) : Comparable<Employee> {
Line 1,850 ⟶ 2,705:
employees.sort()
for ((name, category) in employees) println("${name.padEnd(6)} : $category")
}</langsyntaxhighlight>
 
{{out}}
Line 1,863 ⟶ 2,718:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def H.sort
{def H.sort.i
Line 1,912 ⟶ 2,767:
David Bernie Walter Adam Joe
19 122 1234 2341 5531
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
Line 1,918 ⟶ 2,773:
<br>
The method used here to simulate a compound structure can only hold pairs of terms, since LB arrays ar 1D or 2D. More complicated associated arrays could be stored in delimiter-separated string arrays.
<syntaxhighlight lang="lb">
<lang lb>
N =20
dim IntArray$( N, 2)
Line 1,937 ⟶ 2,792:
print IntArray$( i, 1), IntArray$( i, 2)
next i
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function sorting( a, b )
return a[1] < b[1]
end
Line 1,949 ⟶ 2,804:
for _, v in ipairs( tab ) do
print( unpack(v) )
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,958 ⟶ 2,813:
Checkit3 same as CheckIt3 except values are groups, which now have only a x as value, but we can add more.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Flush ' empty stack of values
Line 2,054 ⟶ 2,909:
}
Checkit3
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,074 ⟶ 2,929:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">events = {{"2009-12-25", "Christmas Day"}, {"2009-04-22",
"Earth Day"}, {"2009-09-07", "Labor Day"}, {"2009-07-04",
"Independence Day"}, {"2009-10-31", "Halloween"}, {"2009-05-25",
Line 2,087 ⟶ 2,942:
name = 2;
SortBy[events, #[[name]] &] // Grid
SortBy[events, #[[date]] &] // Grid</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">2009-12-25 Christmas Day
2009-04-22 Earth Day
2009-10-31 Halloween
Line 2,118 ⟶ 2,973:
2009-11-26 Thanksgiving
2009-12-25 Christmas Day
2009-12-31 New Year's Eve</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn keyCmp comp1 comp2 =
(
case of
Line 2,133 ⟶ 2,988:
people = #(#("joe", 39), #("dave", 37), #("bob", 42))
qsort people keyCmp
print people</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,190 ⟶ 3,045:
else signal IllegalArgumentException('Arguments must be of type PairBean')
return cRes
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,198 ⟶ 3,053:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import algorithm, futuresugar
 
var people = @{"joe": 120, "foo": 31, "bar": 51}
sort(people, (x,y) => cmp(x[0], y[0]))
echo people</langsyntaxhighlight>
{{Out}}
Output:
<pre>@[(Field0: "bar", Field1: 51), (Field0: "foo", Field1: 31), (Field0: "joe", Field1: 120)]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Collection;
 
Line 2,252 ⟶ 3,107:
}
}
</syntaxhighlight>
</lang>
 
<pre>
Line 2,264 ⟶ 3,119:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">@interface Pair : NSObject {
NSString *name;
NSString *value;
Line 2,318 ⟶ 3,173:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let people = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)];;
val people : (string * int) list =
[("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)]
# let sortedPeopleByVal = List.sort (fun (_, v1) (_, v2) -> compare v1 v2) people;;
val sortedPeopleByVal : (string * int) list =
[("Harry", 2); ("Bob", 8); ("Alice", 9); ("Joe", 12)]</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">[["Joe",5531], ["Adam",2341], ["Bernie",122], ["David",19]] sortBy(#first) println</langsyntaxhighlight>
{{out}}
<pre>
[[Adam, 2341], [Bernie, 122], [David, 19], [Joe, 5531]]
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(import (scheme char))
 
(define (comp a b)
(string-ci<? (a 'name #f) (b 'name #f)))
 
(for-each print
(sort comp (list
{ 'name "David"
'value "Manager" }
{ 'name "Alice"
'value "Sales" }
{ 'name "Joanna"
'value "Director" }
{ 'name "Henry"
'value "Admin" }
{ 'name "Tim"
'value "Sales" }
{ 'name "Juan"
'value "Admin" })))
</syntaxhighlight>
{{Out}}
<pre>
#ff((name . Alice) (value . Sales))
#ff((name . David) (value . Manager))
#ff((name . Henry) (value . Admin))
#ff((name . Joanna) (value . Director))
#ff((name . Juan) (value . Admin))
#ff((name . Tim) (value . Sales))
</pre>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
a = .array~new
 
Line 2,393 ⟶ 3,280:
-- perform the comparison on the names
return -left~name~compareTo(right~name)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,422 ⟶ 3,309:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
People = [person(name:joe value:3)
person(name:bill value:4)
Line 2,434 ⟶ 3,321:
}
in
{ForAll SortedPeople Show}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
The flag "2" means that lexicographic sorting is to be used; the "1" means that the array is to be sorted using the first element of each constituent vector.
<langsyntaxhighlight lang="parigp">vecsort([["name", "value"],["name2", "value2"]], 1, 2)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,445 ⟶ 3,332:
=={{header|Perl}}==
Sort by name using cmp to compare strings:
<langsyntaxhighlight lang="perl">@people = (['joe', 120], ['foo', 31], ['bar', 51]);
@people = sort { $a->[0] cmp $b->[0] } @people;</langsyntaxhighlight>
 
Sort by number using <=> to compare numbers:
<langsyntaxhighlight lang="perl">@people = (['joe', 120], ['foo', 31], ['bar', 51]);
@people = sort { $a->[1] <=> $b->[1] } @people;</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
The standard sort compares the first element, then 2nd, 3rd, etc. A custom_sort or sort_columns can be used to sort by other elements.<br>
Elements can be any mix of types, with atoms (ie ints/floats) deemed less than sequences/strings.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>sequence s = {{"grass","green"},{"snow","white"},{"sky","blue"},{"cherry","red"},{0,1.2},{3.4,-1}}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"grass"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"green"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"snow"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"white"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"sky"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"blue"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"cherry"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"red"</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.2</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3.4</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
 
?sort(s)
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
function compare_col2(sequence a, b) return compare(a[2],b[2]) end function
<span style="color: #008080;">function</span> <span style="color: #000000;">compare_col2</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?custom_sort(routine_id("compare_col2"),s)
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">compare_col2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
?sort_columns(s,{2}) -- 0.8.0+, same result as above w/o needing an explicit comparison routine</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sort_columns</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 0.8.0+, same result as above w/o needing an explicit comparison routine</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,467 ⟶ 3,357:
{{3.4,-1},{0,1.2},{"sky","blue"},{"grass","green"},{"cherry","red"},{"snow","white"}}
</pre>
 
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def minverse
Line 2,484 ⟶ 3,373:
 
/# sorted by second component #/
f map sort f map print</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
By default, the [http://software-lab.de/doc/refS.html#sort sort] function in
PicoLisp returns an ascending list (of any type)
<langsyntaxhighlight PicoLisplang="picolisp">: (sort '(("def" 456) ("abc" 789) ("ghi" 123)))
-> (("abc" 789) ("def" 456) ("ghi" 123))</langsyntaxhighlight>
To sort by a certain sub-element, the function
[http://software-lab.de/doc/refB.html#by by] can be used. For example, to
sort by the first element
<langsyntaxhighlight PicoLisplang="picolisp">: (by car sort '(("def" 456) ("abc" 789) ("ghi" 123)))
-> (("abc" 789) ("def" 456) ("ghi" 123))</langsyntaxhighlight>
or by the second element
<langsyntaxhighlight PicoLisplang="picolisp">: (by cadr sort '(("def" 456) ("abc" 789) ("ghi" 123)))
-> (("ghi" 123) ("def" 456) ("abc" 789))</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 2,504 ⟶ 3,393:
{{works with|PowerShell|4.0}}
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
$list = @{
"def" = "one"
Line 2,514 ⟶ 3,403:
}
$list.GetEnumerator() | sort {-($PSItem.Name).length}, Name
</langsyntaxhighlight>
<b>Output:</b>
<pre>
Line 2,535 ⟶ 3,424:
 
'''Example'''
<langsyntaxhighlight PureBasiclang="purebasic">Structure MyPair ; Define a structured data type
Name$
Value.i
Line 2,567 ⟶ 3,456:
; Wait for user...
PrintN(#CRLF$+"Press ENTER to exit"):Input()
EndIf</langsyntaxhighlight>
 
'''Outputs
Line 2,583 ⟶ 3,472:
Recent versions of Python provide the ''sorted()'' built-in that works on any iterable.
 
<langsyntaxhighlight lang="python">people = [('joe', 120), ('foo', 31), ('bar', 51)]
sorted(people)</langsyntaxhighlight>
Which leaves <code>people</code> with the value:
<langsyntaxhighlight lang="python">[('bar', 51), ('foo', 31), ('joe', 120)]</langsyntaxhighlight>
 
<br>The most Pythonic (and fastest) version is to use itemgetter together with the key parameter to <code>sort</code> resp. <code>sorted</code> to perform the [[wp:Decorate-sort-undecorate|Decorate-sort-undecorate]] pattern:
 
<langsyntaxhighlight lang="python">from operator import itemgetter
people = [(120, 'joe'), (31, 'foo'), (51, 'bar')]
people.sort(key=itemgetter(1))</langsyntaxhighlight>
Which leaves <code>people</code> with the value:
<langsyntaxhighlight lang="python">[(51, 'bar'), (31, 'foo'), (120, 'joe')]</langsyntaxhighlight>
 
=={{header|R}}==
In R, vectors can have names associated with any of its elements. The data is taken from the Common Lisp example.
<langsyntaxhighlight Rlang="r">sortbyname <- function(x, ...) x[order(names(x), ...)]
x <- c(texas=68.9, ohio=87.8, california=76.2, "new york"=88.2)
sortbyname(x)</langsyntaxhighlight>
california new york ohio texas
76.2 88.2 87.8 68.9
 
<langsyntaxhighlight Rlang="r">sortbyname(x, decreasing=TRUE)</langsyntaxhighlight>
texas ohio new york california
68.9 87.8 88.2 76.2
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,620 ⟶ 3,509:
(sort data string<? #:key (compose1 symbol->string car))
;; --> '((Adam 2341) (Bernie 122) (David 19) (Joe 5531) (Walter 1234))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.05}}
<syntaxhighlight lang="raku" perl6line>my class Employee {
has Str $.name;
has Rat $.wage;
Line 2,643 ⟶ 3,532:
say @orderedByName.join(' ');
say "Team ordered by wage (ascending order):";
say @orderedByWage.join(' ');</langsyntaxhighlight>
this produces the following output:
<pre>Team ordered by name (ascending order):
Line 2,654 ⟶ 3,543:
=={{header|REXX}}==
This version sorts the structure by color; &nbsp; as entered (built), &nbsp; the structure is ordered by value (percent).
<langsyntaxhighlight lang="rexx">/*REXX program sorts an array of composite structures (which has two classes of data). */
#=0/* (which has two classes of data). /*number elements in structure (so far)*/
namex.='tan'0 ; value= 0; call add name,value /*tan peanut M&M's are 0% of total /*number elements in structure (so far)*/
name=Call add 'orangetan'; value=10; , call0 add name,value /*orange " /*tan " peanut M&M's are " 100% of " " total*/
name=Call add 'yelloworange';,10 value=20; call add name,value /*yelloworange " " " 2010% " " */
name=Call add 'greenyellow',20 ; value=20; call add name,value /*green yellow " " " 20% " " */
name=Call add 'redgreen' ,20 ; value=20; call add name,value /*red green " " " 20% " " */
name=Call add 'brownred' ; value=30;,20 call add name,value /*brownred " " " 3020% " " */
Call add 'brown' ,30 /*brown " " " 30% " " */
call show 'before sort', #
Call show 'before sort'
say copies('▒', 70)
Say copies('¦', 70)
call xSort #
Call xSort
call show ' after sort', #
call show ' after sort'
exit /*stick a fork in it, we're all done. */
Exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*--------------------------------------------------------------------*/
add: procedure expose # @.; #=#+1 /*bump the number of structure entries.*/
add: Procedure Expose x.
@.#.color=arg(1); @.#.pc=arg(2) /*construct a entry of the structure. */
z=x.0+1 /* bump the number of structure entry */
return
x.z.color=arg(1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedurex.z.pc=arg(2) expose @.; do j=1 for arg(2) /*2nd arg≡numberconstruct an entry of the structure elements.*/
x.0=z
say right(arg(1),30) right(@.j.color,9) right(@.j.pc,4)'%'
Return
end /*j*/ /* [↑] display what, name, value. */
/*--------------------------------------------------------------------*/
return
show: Procedure Expose x.
/*──────────────────────────────────────────────────────────────────────────────────────*/
Do i=1 To x.0
xSort: procedure expose @.; parse arg N; h=N
/* display what name value. do while h>1; h=h%2*/
Say right(arg(1),30) right(x.i.color,9) right(x.i.pc,4)'%'
do i=1 for N-h; j=i; k=h+i
End
do while @.k.color<@.j.color /*swap elements.*/
Return
_=@.j.color; @.j.color=@.k.color; @.k.color=_
/*--------------------------------------------------------------------*/
_=@.j.pc; @.j.pc =@.k.pc; @.k.pc =_
xsort: Procedure Expose x.
if h>=j then leave; j=j-h; k=k-h
h=x.0
end /*while @.k.color ···*/
Do While h>1
end /*i*/
h=h%2
end /*while h>1*/
Do i=1 For return</lang>x.0-h
j=i
k=h+i
Do While x.k.color<x.j.color
_=x.j.color /* swap elements. */
x.j.color=x.k.color
x.k.color=_
_=x.j.pc
x.j.pc=x.k.pc
x.k.pc=_
If h>=j Then
Leave
j=j-h
k=k-h
End
End
End
Return</syntaxhighlight>
'''output''' &nbsp; when using the (internal) default inputs:
<pre>
Line 2,706 ⟶ 3,612:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList= sort([:Eight = 8, :Two = 2, :Five = 5, :Nine = 9, :One = 1,
:Three = 3, :Six = 6, :Seven = 7, :Four = 4, :Ten = 10] , 2)
Line 2,712 ⟶ 3,618:
? item[1] + space(10-len(item[1])) + item[2]
next
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,729 ⟶ 3,635:
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">Person = Struct.new(:name,:value) do
def to_s; "name:#{name}, value:#{value}" end
end
Line 2,739 ⟶ 3,645:
puts list.sort_by{|x|x.name}
puts
puts list.sort_by(&:value)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,754 ⟶ 3,660:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">sqliteconnect #mem, ":memory:" ' create in memory db
mem$ = "CREATE TABLE people(num integer, name text,city text)"
#mem execute(mem$)
Line 2,770 ⟶ 3,676:
city$ = #row city$()
print num;" ";name$;" ";city$
WEND</langsyntaxhighlight><pre>3 Ben Seneca
5 Frank Houston
2 Fred Oregon
Line 2,778 ⟶ 3,684:
=={{header|Rust}}==
{{trans|Kotlin}}
<langsyntaxhighlight Rustlang="rust">use std::cmp::Ordering;
 
#[derive(Debug)]
Line 2,828 ⟶ 3,734:
println!("{:<6} : {}", e.name, e.category);
}
}</langsyntaxhighlight>
{{out}}
<pre>Alice : Sales
Line 2,838 ⟶ 3,744:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">case class Pair(name:String, value:Double)
val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855))
input.sortBy(_.name) // Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855))
Line 2,844 ⟶ 3,750:
// alternative versions:
input.sortBy(struct => (struct.name, struct.value)) // additional sort field (name first, then value)
input.sortWith((a,b) => a.name.compareTo(b.name) < 0) // arbitrary comparison function</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: pair is new struct
Line 2,885 ⟶ 3,791:
writeln(aPair);
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 2,897 ⟶ 3,803:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Declare an array of pairs
var people = [['joe', 120], ['foo', 31], ['bar', 51]];
 
Line 2,907 ⟶ 3,813:
 
# Display the sorted array
say people;</langsyntaxhighlight>
 
{{out}}
Line 2,913 ⟶ 3,819:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
CLASS COMPARABLE;;
Line 2,981 ⟶ 3,887:
OUTIMAGE;
END.</langsyntaxhighlight>
{{out}}
<pre>ADAM 2341
Line 2,990 ⟶ 3,896:
 
=={{header|SQL}}==
We can treat the array of data structures as a table. An <code>order by</code> clause in a query will sort the data.<langsyntaxhighlight lang="sql">-- setup
create table pairs (name varchar(16), value varchar(16));
insert into pairs values ('Fluffy', 'cat');
Line 2,996 ⟶ 3,902:
insert into pairs values ('Francis', 'fish');
-- order them by name
select * from pairs order by name;</langsyntaxhighlight>
{{out}}
<pre>NAME VALUE
Line 3,006 ⟶ 3,912:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension Sequence {
func sorted<Value>(
on: KeyPath<Element, Value>,
Line 3,026 ⟶ 3,932:
let c = Person(name: "charlie", role: "driver")
 
print([c, b, a].sorted(on: \.name, using: <))</langsyntaxhighlight>
 
{{out}}
Line 3,034 ⟶ 3,940:
=={{header|Tcl}}==
Modeling the data structure being sorted as a list (a common Tcl practice):
<langsyntaxhighlight lang="tcl">set people {{joe 120} {foo 31} {bar 51}}
# sort by the first element of each pair
lsort -index 0 $people</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
With this language, everything is a string. My list of pairs is a string where a colon ":" separates "name:value", and a newline separates different pairs. Then I can use <tt>sort -t: -k1,1</tt> to sort the pairs by name.
 
<langsyntaxhighlight lang="bash">list="namez:order!
name space:in
name1:sort
Line 3,068 ⟶ 3,974:
 
echo "Sorted list:"
dumplist</langsyntaxhighlight>
 
Output: <pre>Original list:
Line 3,085 ⟶ 3,991:
The built in sort operator, -<, can be parameterized by an
anonymous field specification and/or a relational predicate.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#cast %sWLW
Line 3,093 ⟶ 3,999:
(
-<&l <('z','a'),('x','c'),('y','b')>, # sorted by the left
-<&r <('z','a'),('x','c'),('y','b')>) # sorted by the right</langsyntaxhighlight>
output:
<pre>(
Line 3,101 ⟶ 4,007:
a more verbose example, showing a list of records of a user defined type sorted by a named field:
 
<langsyntaxhighlight Ursalalang="ursala">#import std
 
person :: name %s value %s
Line 3,114 ⟶ 4,020:
#cast _person%L
 
example = (lleq+ ~name~~)-< people</langsyntaxhighlight>
output:
<pre>
Line 3,124 ⟶ 4,030:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Cmp, Sort, Comparable
 
class Pair is Comparable {
Line 3,151 ⟶ 4,057:
Sort.insertion(pairs)
System.print("\nAfter sorting:")
System.print(" " + pairs.join("\n "))</langsyntaxhighlight>
 
{{out}}
Line 3,169 ⟶ 4,075:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
Line 3,200 ⟶ 4,106:
for I:= 0 to Entries-1 do \show sorted entries
[ChOut(0, Dict(I,0)); ChOut(0, ^ ); Text(0, @Dict(I,1)); CrLf(0)];
]</langsyntaxhighlight>
 
{{out}}
Line 3,212 ⟶ 4,118:
=={{header|zkl}}==
The list of lists way is available or:
<langsyntaxhighlight lang="zkl">class P{var name,value;
fcn init(nm,val){name,value=vm.arglist}
fcn __opLT(p){name<p.name} // implementation of P1 < P2
Line 3,219 ⟶ 4,125:
p:=List(P("sam","a"),P("fred","b"),P("chris","c"));
p.sort();
p.apply("name"); //-->L("chris","fred","sam")</langsyntaxhighlight>
9,476

edits