Sort using a custom comparator: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 15: Line 15:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V strings = ‘here are Some sample strings to be sorted’.split(‘ ’)
<syntaxhighlight lang="11l">V strings = ‘here are Some sample strings to be sorted’.split(‘ ’)


print(sorted(strings, key' x -> (-x.len, x.uppercase())))</lang>
print(sorted(strings, key' x -> (-x.len, x.uppercase())))</syntaxhighlight>


{{out}}
{{out}}
Line 26: Line 26:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program customSort64.s */
/* program customSort64.s */
Line 384: Line 384:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Name : London country : UK
Name : London country : UK
Line 411: Line 411:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE PTR="CARD"
<syntaxhighlight lang="action!">DEFINE PTR="CARD"


PROC PrintArray(PTR ARRAY a INT size)
PROC PrintArray(PTR ARRAY a INT size)
Line 488: Line 488:
Test(a,24,CustomComparator)
Test(a,24,CustomComparator)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_using_a_custom_comparator.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_using_a_custom_comparator.png Screenshot from Atari 8-bit computer]
Line 506: Line 506:
{{incorrect}}
{{incorrect}}
{{works with|GNAT|}}
{{works with|GNAT|}}
<lang ada>
<syntaxhighlight lang="ada">
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
Line 614: Line 614:
Put_Line("Sorted list:");
Put_Line("Sorted list:");
Put(Strings);
Put(Strings);
end Custom_Compare;</lang>
end Custom_Compare;</syntaxhighlight>
{{out}}
{{out}}
<pre>Unsorted list:
<pre>Unsorted list:
Line 655: Line 655:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
The Algol 68 version of the Quicksort algorithm, modified to use a custom sort routine, as per this task.
The Algol 68 version of the Quicksort algorithm, modified to use a custom sort routine, as per this task.
<lang algol68># define the MODE that will be sorted #
<syntaxhighlight lang="algol68"># define the MODE that will be sorted #
MODE SITEM = STRING;
MODE SITEM = STRING;
#--- Swap function ---#
#--- Swap function ---#
Line 748: Line 748:
quicksort(a, compare);
quicksort(a, compare);
print(("After :"));FOR i FROM LWB a TO UPB a DO print((" ",a[i])) OD; print((newline))
print(("After :"));FOR i FROM LWB a TO UPB a DO print((" ",a[i])) OD; print((newline))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 759: Line 759:
AppleScript is not itself well equipped with sorting functions, but from Yosemite onwards we can make some use of ObjC classes. While a classic comparator function can not readily be passed from AppleScript to ObjC, we can at least write a custom function which lifts atomic values into records (with keys to base and derivative values), and also passes a sequence of (key, bool) pairs, where the bool expresses the choice between ascending and descending order for the paired key:
AppleScript is not itself well equipped with sorting functions, but from Yosemite onwards we can make some use of ObjC classes. While a classic comparator function can not readily be passed from AppleScript to ObjC, we can at least write a custom function which lifts atomic values into records (with keys to base and derivative values), and also passes a sequence of (key, bool) pairs, where the bool expresses the choice between ascending and descending order for the paired key:


<lang AppleScript>use framework "Foundation"
<syntaxhighlight lang="applescript">use framework "Foundation"


-- SORTING LISTS OF ATOMIC (NON-RECORD) DATA WITH A CUSTOM SORT FUNCTION
-- SORTING LISTS OF ATOMIC (NON-RECORD) DATA WITH A CUSTOM SORT FUNCTION
Line 855: Line 855:
sortBy(lengthDownAZup, xs)
sortBy(lengthDownAZup, xs)
end run</lang>
end run</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{"Sao Paulo", "Shanghai", "Beijing", "Karachi", "Delhi", "Dhaka", "Lagos"}</pre>
<pre>{"Sao Paulo", "Shanghai", "Beijing", "Karachi", "Delhi", "Dhaka", "Lagos"}</pre>
Line 863: Line 863:
Putting values into records temporarily can sometimes be necessary with ASObjC sorts so that sorting can be done on the equivalent NSDictionaries' keys. But in fact NSStrings can be sorted on the keys <tt>"length"</tt> and <tt>"self"</tt>:
Putting values into records temporarily can sometimes be necessary with ASObjC sorts so that sorting can be done on the equivalent NSDictionaries' keys. But in fact NSStrings can be sorted on the keys <tt>"length"</tt> and <tt>"self"</tt>:


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 873: Line 873:
tell arrayOfStrings to sortUsingDescriptors:({descendingByLength, ascendingLexicographically})
tell arrayOfStrings to sortUsingDescriptors:({descendingByLength, ascendingLexicographically})


return arrayOfStrings as list</lang>
return arrayOfStrings as list</syntaxhighlight>


{{output}}
{{output}}
Line 882: Line 882:
While vanilla AppleScript doesn't have sort facilities of its own, a customisable sort written in vanilla, such as [https://macscripter.net/viewtopic.php?pid=194430#p194430 this one on MacScripter], can be fed user-defined comparison handlers to do practically any kind of sorting. The following assumes that the customisable sort just mentioned has been compiled and saved in a suitable "Script Libraries" folder as "Custom Iterative Ternary Merge Sort.scpt":
While vanilla AppleScript doesn't have sort facilities of its own, a customisable sort written in vanilla, such as [https://macscripter.net/viewtopic.php?pid=194430#p194430 this one on MacScripter], can be fed user-defined comparison handlers to do practically any kind of sorting. The following assumes that the customisable sort just mentioned has been compiled and saved in a suitable "Script Libraries" folder as "Custom Iterative Ternary Merge Sort.scpt":


<lang applescript>use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
use sorter : script "Custom Iterative Ternary Merge Sort"
use sorter : script "Custom Iterative Ternary Merge Sort"


Line 901: Line 901:
-- Sort the whole list using the above customiser.
-- Sort the whole list using the above customiser.
tell sorter to sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
tell sorter to sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
return listOfText</lang>
return listOfText</syntaxhighlight>


{{output}}
{{output}}
Line 908: Line 908:
=={{header|ATS}}==
=={{header|ATS}}==


<lang ATS>(* The following demonstrates a few ways to customize the
<syntaxhighlight lang="ats">(* The following demonstrates a few ways to customize the
comparator. *)
comparator. *)


Line 1,076: Line 1,076:
println! sorted4;
println! sorted4;
println! sorted5
println! sorted5
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,088: Line 1,088:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>numbers = 5,3,7,9,1,13,999,-4
<syntaxhighlight lang="autohotkey">numbers = 5,3,7,9,1,13,999,-4
strings = Here,are,some,sample,strings,to,be,sorted
strings = Here,are,some,sample,strings,to,be,sorted
Sort, numbers, F IntegerSort D,
Sort, numbers, F IntegerSort D,
Line 1,101: Line 1,101:
StringLengthSort(a1, a2){
StringLengthSort(a1, a2){
return strlen(a1) - strlen(a2)
return strlen(a1) - strlen(a2)
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
For GAWK, this uses the inbuilt descending numeric ordering and a custom comparison routine for caseless string comparison.
For GAWK, this uses the inbuilt descending numeric ordering and a custom comparison routine for caseless string comparison.
May need modification for TAWK.
May need modification for TAWK.
<lang AWK># syntax: GAWK -f SORT_USING_A_CUSTOM_COMPARATOR.AWK
<syntaxhighlight lang="awk"># syntax: GAWK -f SORT_USING_A_CUSTOM_COMPARATOR.AWK
#
#
# sorting:
# sorting:
Line 1,138: Line 1,138:
l2 = tolower( i2 );
l2 = tolower( i2 );
return ( ( l1 < l2 ) ? -1 : ( ( l1 == l2 ) ? 0 : 1 ) );
return ( ( l1 < l2 ) ? -1 : ( ( l1 == l2 ) ? 0 : 1 ) );
} # caselessCompare</lang>
} # caselessCompare</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,186: Line 1,186:
To sort ASCII strings, use the strsort or lexsort utilities to sort alphabetically and lexicographically, respectively.
To sort ASCII strings, use the strsort or lexsort utilities to sort alphabetically and lexicographically, respectively.


<lang babel>babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") strsort ! lsstr !
<syntaxhighlight lang="babel">babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") strsort ! lsstr !
( "Here" "are" "be" "sample" "some" "sorted" "strings" "to" )
( "Here" "are" "be" "sample" "some" "sorted" "strings" "to" )
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") lexsort ! lsstr !
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") lexsort ! lsstr !
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</lang>
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</syntaxhighlight>


If you want to sort UTF-8 encoded Unicode strings, first convert to array-string form using the str2ar operator, then sort using the strcmp operator. To sort lexicographically, use the arcmp operator. The following examples illustrate each case:
If you want to sort UTF-8 encoded Unicode strings, first convert to array-string form using the str2ar operator, then sort using the strcmp operator. To sort lexicographically, use the arcmp operator. The following examples illustrate each case:


<lang babel>babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") {str2ar} over ! {strcmp 0 lt?} lssort ! {ar2str} over ! lsstr !
<syntaxhighlight lang="babel">babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") {str2ar} over ! {strcmp 0 lt?} lssort ! {ar2str} over ! lsstr !
( "Here" "are" "be" "some" "sample" "sorted" "strings" "to" )
( "Here" "are" "be" "some" "sample" "sorted" "strings" "to" )
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") {str2ar} over ! {arcmp 0 lt?} lssort ! {ar2str} over ! lsstr !
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") {str2ar} over ! {arcmp 0 lt?} lssort ! {ar2str} over ! lsstr !
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</lang>
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</syntaxhighlight>


You can sort a list of any kind of structure you like using the lssort utility. Use the lt? numerical comparison operator for sorting numerical lists:
You can sort a list of any kind of structure you like using the lssort utility. Use the lt? numerical comparison operator for sorting numerical lists:


<lang babel>babel> ( 5 6 8 4 5 3 9 9 4 9 ) {lt?} lssort ! lsnum !
<syntaxhighlight lang="babel">babel> ( 5 6 8 4 5 3 9 9 4 9 ) {lt?} lssort ! lsnum !
( 3 4 4 5 5 6 8 9 9 9 )</lang>
( 3 4 4 5 5 6 8 9 9 9 )</syntaxhighlight>


You can even shuffle a list with lssort using the randlf operator (your results will probably differ):
You can even shuffle a list with lssort using the randlf operator (your results will probably differ):


<lang babel>babel> (1 2 3 4 5 6 7 8 9) {1 randlf 2 rem} lssort ! lsnum !
<syntaxhighlight lang="babel">babel> (1 2 3 4 5 6 7 8 9) {1 randlf 2 rem} lssort ! lsnum !
( 7 5 9 6 2 4 3 1 8 )</lang>
( 7 5 9 6 2 4 3 1 8 )</syntaxhighlight>


To sort complex objects, you need to access the relevant field in each object, and then provide the result of comparing them. For example, to sort a list of pairs by first number:
To sort complex objects, you need to access the relevant field in each object, and then provide the result of comparing them. For example, to sort a list of pairs by first number:


<lang babel>
<syntaxhighlight lang="babel">
babel> 20 lsrange ! {1 randlf 2 rem} lssort ! 2 group ! --> this creates a shuffled list of pairs
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
babel> dup {lsnum !} ... --> display the shuffled list, pair-by-pair
Line 1,234: Line 1,234:
( 15 13 )
( 15 13 )
( 17 3 )
( 17 3 )
( 18 9 )</lang>
( 18 9 )</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}><
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}><
{"ADD" "Abc" "Acb" "acb" "acc"}
{"ADD" "Abc" "Acb" "acb" "acc"}
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb
{"Abc" "acb" "Acb" "acc" "ADD"}
{"Abc" "acb" "Acb" "acc" "ADD"}
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
{{works with|POSIX|.1-2001}}
{{works with|POSIX|.1-2001}}


<lang c>#include <stdlib.h> /* for qsort */
<syntaxhighlight lang="c">#include <stdlib.h> /* for qsort */
#include <string.h> /* for strlen */
#include <string.h> /* for strlen */
#include <strings.h> /* for strcasecmp */
#include <strings.h> /* for strcasecmp */
Line 1,269: Line 1,269:
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 1,279: Line 1,279:
C# allows you to specify a custom compare to the built in sort method on a list
C# allows you to specify a custom compare to the built in sort method on a list


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 1,318: Line 1,318:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,360: Line 1,360:




<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 1,399: Line 1,399:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
{{works with|g++|4.1.2}}
{{works with|g++|4.1.2}}
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <string>
#include <string>
#include <cctype>
#include <cctype>
Line 1,431: Line 1,431:
std::sort(strings, strings+8, compare());
std::sort(strings, strings+8, compare());
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {


value strings = [
value strings = [
Line 1,447: Line 1,447:
sorted.each(print);
sorted.each(print);
}</lang>
}</syntaxhighlight>


=={{header|Clean}}==
=={{header|Clean}}==
<lang clean>import StdEnv
<syntaxhighlight lang="clean">import StdEnv


less s1 s2
less s1 s2
Line 1,460: Line 1,460:
lower s = {toLower c \\ c <-: s}
lower s = {toLower c \\ c <-: s}


Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"]</lang>
Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"]</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Clojure's ''sort'' function has a 2-argument version where the first argument is a ''java.util.Comparator'', and the second is the collection to be sorted. Thus the heart of this version is a comparator function that satisfies the problem spec. What makes this work is that all Clojure functions (thus ''rosetta-code'' defined here) implement the ''java.util.Comparator'' interface.
Clojure's ''sort'' function has a 2-argument version where the first argument is a ''java.util.Comparator'', and the second is the collection to be sorted. Thus the heart of this version is a comparator function that satisfies the problem spec. What makes this work is that all Clojure functions (thus ''rosetta-code'' defined here) implement the ''java.util.Comparator'' interface.
<lang clojure>(defn rosetta-compare [s1 s2]
<syntaxhighlight lang="clojure">(defn rosetta-compare [s1 s2]
(let [len1 (count s1), len2 (count s2)]
(let [len1 (count s1), len2 (count s2)]
(if (= len1 len2)
(if (= len1 len2)
Line 1,472: Line 1,472:
(println
(println
(sort rosetta-compare
(sort rosetta-compare
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]))</lang>
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]))</syntaxhighlight>


{{out}}
{{out}}
Line 1,480: Line 1,480:


An alternative, using <tt>sort-by</tt>:
An alternative, using <tt>sort-by</tt>:
<lang clojure>(sort-by (juxt (comp - count) #(.toLowerCase %))
<syntaxhighlight lang="clojure">(sort-by (juxt (comp - count) #(.toLowerCase %))
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"])</lang>
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"])</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 1,488: Line 1,488:
For example, to sort strings case-insensitively in ascending order:
For example, to sort strings case-insensitively in ascending order:


<lang lisp>CL-USER> (defvar *strings*
<syntaxhighlight lang="lisp">CL-USER> (defvar *strings*
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
*STRINGS*
*STRINGS*
CL-USER> (sort *strings* #'string-lessp)
CL-USER> (sort *strings* #'string-lessp)
("Actor" "Adam" "add" "apple" "base" "butter" "Cat" "Level" "quit" "Xmas"
("Actor" "Adam" "add" "apple" "base" "butter" "Cat" "Level" "quit" "Xmas"
"zero")</lang>
"zero")</syntaxhighlight>


You can also provide an optional key function which maps each element to a key. The keys are then compared using the comparator. For example, to sort strings by length in descending order:
You can also provide an optional key function which maps each element to a key. The keys are then compared using the comparator. For example, to sort strings by length in descending order:


<lang lisp>CL-USER> (defvar *strings*
<syntaxhighlight lang="lisp">CL-USER> (defvar *strings*
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
*STRINGS*
*STRINGS*
CL-USER> (sort *strings* #'> :key #'length)
CL-USER> (sort *strings* #'> :key #'length)
("butter" "apple" "Level" "Actor" "Adam" "zero" "Xmas" "quit" "base"
("butter" "apple" "Level" "Actor" "Adam" "zero" "Xmas" "quit" "base"
"Cat" "add")</lang>
"Cat" "add")</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.string, std.algorithm, std.typecons;
<syntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.typecons;


void main() {
void main() {
Line 1,512: Line 1,512:
.schwartzSort!q{ tuple(-a.length, a.toUpper) }
.schwartzSort!q{ tuple(-a.length, a.toUpper) }
.writeln;
.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>["strings", "sample", "sorted", "here", "Some", "are", "be", "to"]</pre>
<pre>["strings", "sample", "sorted", "here", "Some", "are", "be", "to"]</pre>
Line 1,519: Line 1,519:
The more natural and efficient way to solve this problem is to use <code>std.algorith.multiSort</code>.
The more natural and efficient way to solve this problem is to use <code>std.algorith.multiSort</code>.
But currently it's less convenient because it can't be used with the UFCSyntax (same output):
But currently it's less convenient because it can't be used with the UFCSyntax (same output):
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.algorithm;
import std.stdio, std.string, std.algorithm;


Line 1,525: Line 1,525:
parts.multiSort!(q{a.length > b.length}, q{a.toUpper < b.toUpper});
parts.multiSort!(q{a.length > b.length}, q{a.toUpper < b.toUpper});
parts.writeln;
parts.writeln;
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program SortWithCustomComparator;
<syntaxhighlight lang="delphi">program SortWithCustomComparator;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,548: Line 1,548:
Result := CompareText(Left, Right);
Result := CompareText(Left, Right);
end));
end));
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>/** returns a if it is nonzero, otherwise b() */
<syntaxhighlight lang="e">/** returns a if it is nonzero, otherwise b() */
def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } }
def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } }


Line 1,558: Line 1,558:
nonzeroOr(b.size().op__cmp(a.size()),
nonzeroOr(b.size().op__cmp(a.size()),
fn { a.compareToIgnoreCase(b) })
fn { a.compareToIgnoreCase(b) })
})</lang>
})</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==


{{works with|EDT|}}
{{works with|EDT|}}
<lang EGL>program SortExample
<syntaxhighlight lang="egl">program SortExample
function main()
function main()
Line 1,599: Line 1,599:
end
end
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,627: Line 1,627:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import system'culture;
import system'culture;
Line 1,642: Line 1,642:
console.printLine("Ascending order: ", items.clone()
console.printLine("Ascending order: ", items.clone()
.sort:(p,n => p.toUpper(invariantLocale) < n.toUpper(invariantLocale)).asEnumerable())
.sort:(p,n => p.toUpper(invariantLocale) < n.toUpper(invariantLocale)).asEnumerable())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,651: Line 1,651:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>strs = ~w[this is a set of strings to sort This Is A Set Of Strings To Sort]
<syntaxhighlight lang="elixir">strs = ~w[this is a set of strings to sort This Is A Set Of Strings To Sort]


comparator = fn s1,s2 -> if String.length(s1)==String.length(s2),
comparator = fn s1,s2 -> if String.length(s1)==String.length(s2),
Line 1,659: Line 1,659:


# or
# or
IO.inspect Enum.sort_by(strs, fn str -> {-String.length(str), String.downcase(str)} end)</lang>
IO.inspect Enum.sort_by(strs, fn str -> {-String.length(str), String.downcase(str)} end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,668: Line 1,668:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( sort_using_custom_comparator ).
-module( sort_using_custom_comparator ).


Line 1,681: Line 1,681:
longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =< erlang:length(String2) -> false;
longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =< erlang:length(String2) -> false;
longest_first_case_insensitive( _String1, _String2 ) -> true.
longest_first_case_insensitive( _String1, _String2 ) -> true.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,690: Line 1,690:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include sort.e
<syntaxhighlight lang="euphoria">include sort.e
include wildcard.e
include wildcard.e
include misc.e
include misc.e
Line 1,709: Line 1,709:


puts(1,"\n\nSorted:\n")
puts(1,"\n\nSorted:\n")
pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2})</lang>
pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2})</syntaxhighlight>


{{out}}
{{out}}
Line 1,737: Line 1,737:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>let myCompare (s1:string) (s2:string) =
<syntaxhighlight lang="fsharp">let myCompare (s1:string) (s2:string) =
match compare s2.Length s1.Length with
match compare s2.Length s1.Length with
| 0 -> compare (s1.ToLower()) (s2.ToLower())
| 0 -> compare (s1.ToLower()) (s2.ToLower())
Line 1,746: Line 1,746:
let sortedStrings = List.sortWith myCompare strings
let sortedStrings = List.sortWith myCompare strings


printfn "%A" sortedStrings</lang>
printfn "%A" sortedStrings</syntaxhighlight>


{{out}}
{{out}}
Line 1,752: Line 1,752:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: my-compare ( s1 s2 -- <=> )
<syntaxhighlight lang="factor">: my-compare ( s1 s2 -- <=> )
2dup [ length ] compare invert-comparison
2dup [ length ] compare invert-comparison
dup +eq+ = [ drop [ >lower ] compare ] [ 2nip ] if ;
dup +eq+ = [ drop [ >lower ] compare ] [ 2nip ] if ;


{ "this" "is" "a" "set" "of" "strings" "to" "sort" } [ my-compare ] sort</lang>
{ "this" "is" "a" "set" "of" "strings" "to" "sort" } [ my-compare ] sort</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,762: Line 1,762:
The List's sort method can be customised using a custom comparator. This is a method which returns an Int: -1 for less than, 0 for equal, +1 for greater than.
The List's sort method can be customised using a custom comparator. This is a method which returns an Int: -1 for less than, 0 for equal, +1 for greater than.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,783: Line 1,783:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,796: Line 1,796:
Fortran does not have builtin to sort arrays (of numbers or strings), with or without custom comparator; so we need modifying e.g. [[Shell sort#Fortran|this code]] in order to handle strings and to accept a custom comparator.
Fortran does not have builtin to sort arrays (of numbers or strings), with or without custom comparator; so we need modifying e.g. [[Shell sort#Fortran|this code]] in order to handle strings and to accept a custom comparator.


<lang fortran>module sorts_with_custom_comparator
<syntaxhighlight lang="fortran">module sorts_with_custom_comparator
implicit none
implicit none
contains
contains
Line 1,828: Line 1,828:
end do
end do
end subroutine a_sort
end subroutine a_sort
end module sorts_with_custom_comparator</lang>
end module sorts_with_custom_comparator</syntaxhighlight>


Then we have to put our custom comparator in a module (<tt>to_lower</tt> is defined [[Change string case|here]]):
Then we have to put our custom comparator in a module (<tt>to_lower</tt> is defined [[Change string case|here]]):


<lang fortran>module comparators
<syntaxhighlight lang="fortran">module comparators
implicit none
implicit none
contains
contains
Line 1,857: Line 1,857:
end if
end if
end function my_compare
end function my_compare
end module comparators</lang>
end module comparators</syntaxhighlight>


At the end, we can test these:
At the end, we can test these:


<lang fortran>program CustomComparator
<syntaxhighlight lang="fortran">program CustomComparator
use comparators
use comparators
use sorts_with_custom_comparator
use sorts_with_custom_comparator
Line 1,875: Line 1,875:
print *, trim(str(i))
print *, trim(str(i))
end do
end do
end program CustomComparator</lang>
end program CustomComparator</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 23-10-2016
<syntaxhighlight lang="freebasic">' version 23-10-2016
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,925: Line 1,925:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>strings
<pre>strings
Line 1,938: Line 1,938:
=={{header|Frink}}==
=={{header|Frink}}==
The program statement is somewhat naive in saying "lexicographic order" as if it a single, well-defined thing. Lexicographic sorting rules and alphabetization rules vary widely from human language to human language and require a great deal of knowledge of those rules and of Unicode to perform correctly. Frink, however, has knowledge of alphabetization (collation) rules for a large number of human languages and will make you look smart. These are encapsulated in the <CODE>lexicalCompare</CODE> and <CODE>lexicalSort</CODE> functions. By default, these compare based on the language settings defined by your Java Virtual Machine (which should be those for your human language.) The following sorts Unicode correctly according to your human language's conventions. However, see below for a more flexible example that sorts for many of the world's languages!
The program statement is somewhat naive in saying "lexicographic order" as if it a single, well-defined thing. Lexicographic sorting rules and alphabetization rules vary widely from human language to human language and require a great deal of knowledge of those rules and of Unicode to perform correctly. Frink, however, has knowledge of alphabetization (collation) rules for a large number of human languages and will make you look smart. These are encapsulated in the <CODE>lexicalCompare</CODE> and <CODE>lexicalSort</CODE> functions. By default, these compare based on the language settings defined by your Java Virtual Machine (which should be those for your human language.) The following sorts Unicode correctly according to your human language's conventions. However, see below for a more flexible example that sorts for many of the world's languages!
<lang frink>f = {|a,b|
<syntaxhighlight lang="frink">f = {|a,b|
len = length[b] <=> length[a]
len = length[b] <=> length[a]
if len != 0
if len != 0
Line 1,947: Line 1,947:


words = split[%r/\s+/, "Here are some sample strings to be sorted"]
words = split[%r/\s+/, "Here are some sample strings to be sorted"]
println[sort[words, f]]</lang>
println[sort[words, f]]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,954: Line 1,954:


Alternately, here is a surprisingly powerful version of the sorter above that can sort based on the alphabetization rules of a very wide number of human languages. The language for the lexicographic comparison can be specified to the <CODE>lexicalCompare</CODE> function as an ISO 639-1 two-letter language code, or can be even more specific. For example, the following sorts a list of words based on the alphabetization rules for Danish.
Alternately, here is a surprisingly powerful version of the sorter above that can sort based on the alphabetization rules of a very wide number of human languages. The language for the lexicographic comparison can be specified to the <CODE>lexicalCompare</CODE> function as an ISO 639-1 two-letter language code, or can be even more specific. For example, the following sorts a list of words based on the alphabetization rules for Danish.
<lang frink>f = {|a,b,lang| lexicalCompare[a,b,lang] }
<syntaxhighlight lang="frink">f = {|a,b,lang| lexicalCompare[a,b,lang] }


words = ["Ærø", "Aalborg", "Tårnby", "Vejen", "Thisted", "Stevns", "Sønderborg", "Eliasen"]
words = ["Ærø", "Aalborg", "Tårnby", "Vejen", "Thisted", "Stevns", "Sønderborg", "Eliasen"]
println[sort[words, f, "da"]]</lang>
println[sort[words, f, "da"]]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,966: Line 1,966:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>def preceeds( a, b ) = b.length() < a.length() or b.length() == a.length() and a.compareToIgnoreCase( b ) < 0
<syntaxhighlight lang="funl">def preceeds( a, b ) = b.length() < a.length() or b.length() == a.length() and a.compareToIgnoreCase( b ) < 0


println( ["here", "are", "Some", "sample", "strings", "to", "be", "sorted"].sortWith(preceeds) )</lang>
println( ["here", "are", "Some", "sample", "strings", "to", "be", "sorted"].sortWith(preceeds) )</syntaxhighlight>


{{out}}
{{out}}
Line 1,985: Line 1,985:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,011: Line 2,011:
sort.Sort(s)
sort.Sort(s)
fmt.Println(s, "(sorted)")
fmt.Println(s, "(sorted)")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[To tell your name the livelong day To an admiring bog] (original)
<pre>[To tell your name the livelong day To an admiring bog] (original)
Line 2,018: Line 2,018:
=={{header|Groovy}}==
=={{header|Groovy}}==
The "custom comparator" is just a closure attached to the sort method invocation.
The "custom comparator" is just a closure attached to the sort method invocation.
<lang groovy>def strings = "Here are some sample strings to be sorted".split()
<syntaxhighlight lang="groovy">def strings = "Here are some sample strings to be sorted".split()
strings.sort { x, y ->
strings.sort { x, y ->
y.length() <=> x.length() ?: x.compareToIgnoreCase(y)
y.length() <=> x.length() ?: x.compareToIgnoreCase(y)
}
}
println strings</lang>
println strings</syntaxhighlight>


{{out}}
{{out}}
Line 2,029: Line 2,029:
=={{header|Haskell}}==
=={{header|Haskell}}==
{{works with|GHC}}
{{works with|GHC}}
<lang haskell>import Data.Char (toLower)
<syntaxhighlight lang="haskell">import Data.Char (toLower)
import Data.List (sortBy)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Ord (comparing)
Line 2,062: Line 2,062:
]
]
)
)
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>be
<pre>be
Line 2,083: Line 2,083:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main() #: demonstrate various ways to sort a list and string
<syntaxhighlight lang="icon">procedure main() #: demonstrate various ways to sort a list and string
write("Sorting Demo for custom comparator")
write("Sorting Demo for custom comparator")
L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
Line 2,095: Line 2,095:
procedure cmptask(a,b) # sort by descending length and ascending lexicographic order for strings of equal length
procedure cmptask(a,b) # sort by descending length and ascending lexicographic order for strings of equal length
if (*a > *b) | ((*a = *b) & (map(a) << map(b))) then return b
if (*a > *b) | ((*a = *b) & (map(a) << map(b))) then return b
end</lang>
end</syntaxhighlight>


Note(1): This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]].
Note(1): This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]].
Line 2,128: Line 2,128:
Standard utilities <tt>tolower</tt> or <tt>toupper</tt> may be substituted.
Standard utilities <tt>tolower</tt> or <tt>toupper</tt> may be substituted.


<lang j> mycmp=: 1 :'/:u'
<syntaxhighlight lang="j"> mycmp=: 1 :'/:u'
length_and_lex =: (-@:# ; lower)&>
length_and_lex =: (-@:# ; lower)&>
strings=: 'Here';'are';'some';'sample';'strings';'to';'be';'sorted'
strings=: 'Here';'are';'some';'sample';'strings';'to';'be';'sorted'
Line 2,134: Line 2,134:
+-------+------+------+----+----+---+--+--+
+-------+------+------+----+----+---+--+--+
|strings|sample|sorted|Here|some|are|be|to|
|strings|sample|sorted|Here|some|are|be|to|
+-------+------+------+----+----+---+--+--+</lang>
+-------+------+------+----+----+---+--+--+</syntaxhighlight>


Generally speaking, J uses the concept of sorting against a normalized content (which is what <code>length_and_lex</code> provided in the above example). This eliminates a class of errors (which might be conceptualized by using a custom comparator which generates a random number: order would be non-deterministic and sorted order would depend on details of the sorting algorithm) and supports O(n) sorting algorithms such as bin sort (which cannot use comparators).
Generally speaking, J uses the concept of sorting against a normalized content (which is what <code>length_and_lex</code> provided in the above example). This eliminates a class of errors (which might be conceptualized by using a custom comparator which generates a random number: order would be non-deterministic and sorted order would depend on details of the sorting algorithm) and supports O(n) sorting algorithms such as bin sort (which cannot use comparators).
Line 2,140: Line 2,140:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.Comparator;
<syntaxhighlight lang="java5">import java.util.Comparator;
import java.util.Arrays;
import java.util.Arrays;


Line 2,159: Line 2,159:
System.out.print(s + " ");
System.out.print(s + " ");
}
}
}</lang>
}</syntaxhighlight>


Same thing as above
Same thing as above
{{works with|Java|8+}}
{{works with|Java|8+}}
<lang java5>import java.util.Comparator;
<syntaxhighlight lang="java5">import java.util.Comparator;
import java.util.Arrays;
import java.util.Arrays;


Line 2,180: Line 2,180:
System.out.print(s + " ");
System.out.print(s + " ");
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>function lengthSorter(a, b) {
<syntaxhighlight lang="javascript">function lengthSorter(a, b) {
var result = b.length - a.length;
var result = b.length - a.length;
if (result == 0)
if (result == 0)
Line 2,193: Line 2,193:
var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
test.sort(lengthSorter);
test.sort(lengthSorter);
alert( test.join(' ') ); // strings sample sorted Here some are be to</lang>
alert( test.join(' ') ); // strings sample sorted Here some are be to</syntaxhighlight>


Or, abstracting a little for simpler composition of compound and derived searches (ASC and DESC, secondary sorts):
Or, abstracting a little for simpler composition of compound and derived searches (ASC and DESC, secondary sorts):


<lang javascript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 2,317: Line 2,317:
.sort(on(flip(compare), population))
.sort(on(flip(compare), population))
});
});
})();</lang>
})();</syntaxhighlight>


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,395: Line 2,395:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>be
<pre>be
Line 2,421: Line 2,421:


As illustrated in the example, the comparator may be any jq filter, whether or not it is defined as a function.
As illustrated in the example, the comparator may be any jq filter, whether or not it is defined as a function.
<lang jq>def quicksort(cmp):
<syntaxhighlight lang="jq">def quicksort(cmp):
if length < 2 then . # it is already sorted
if length < 2 then . # it is already sorted
else .[0] as $pivot
else .[0] as $pivot
Line 2,442: Line 2,442:
end )
end )
| (.[0] | quicksort(cmp) ) + .[1] + (.[2] | quicksort(cmp) )
| (.[0] | quicksort(cmp) ) + .[1] + (.[2] | quicksort(cmp) )
end ;</lang>
end ;</syntaxhighlight>
Example:
Example:
<lang jq># Sort by string length, breaking ties using ordinary string comparison.
<syntaxhighlight lang="jq"># Sort by string length, breaking ties using ordinary string comparison.
["z", "yz", "ab", "c"]
["z", "yz", "ab", "c"]
| quicksort( (.[0]|length) > (.[1]|length) or ( (.[0]|length) == (.[1]|length) and .[0] < .[1] ) )
| quicksort( (.[0]|length) > (.[1]|length) or ( (.[0]|length) == (.[1]|length) and .[0] < .[1] ) )
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<lang jq>[
<syntaxhighlight lang="jq">[
"ab",
"ab",
"yz",
"yz",
"c",
"c",
"z"
"z"
]</lang>
]</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
My word list source is the opening sentence of Shelly's [http://www.gutenberg.org/cache/epub/84/pg84.txt Frankenstein].
My word list source is the opening sentence of Shelly's [http://www.gutenberg.org/cache/epub/84/pg84.txt Frankenstein].
<lang julia>wl = filter(!isempty, split("""You will rejoice to hear that no disaster has accompanied the
<syntaxhighlight lang="julia">wl = filter(!isempty, split("""You will rejoice to hear that no disaster has accompanied the
commencement of an enterprise which you have regarded with such evil
commencement of an enterprise which you have regarded with such evil
forebodings.""", r"\W+"))
forebodings.""", r"\W+"))
Line 2,465: Line 2,465:
sort!(wl; by=x -> (-length(x), lowercase(x)))
sort!(wl; by=x -> (-length(x), lowercase(x)))
println("\nSorted list:\n - ", join(wl, "\n - "))
println("\nSorted list:\n - ", join(wl, "\n - "))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,522: Line 2,522:
A translation from Java, also showing the seamless interop between Java and Kotlin code.
A translation from Java, also showing the seamless interop between Java and Kotlin code.


<lang kotlin>import java.util.Arrays
<syntaxhighlight lang="kotlin">import java.util.Arrays


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 2,543: Line 2,543:


printArray("Sorted:", strings)
printArray("Sorted:", strings)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,552: Line 2,552:
A more idiomatic version (1.3):
A more idiomatic version (1.3):


<lang kotlin>fun main(args: Array<String>) {
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
println("Unsorted: $strings")
Line 2,560: Line 2,560:


println("Sorted: $sorted")
println("Sorted: $sorted")
}</lang>
}</syntaxhighlight>




Using a custom comparator as requested by task description:
Using a custom comparator as requested by task description:


<lang kotlin>fun main(args: Array<String>) {
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
println("Unsorted: $strings")
Line 2,577: Line 2,577:
println("Sorted: $sorted")
println("Sorted: $sorted")
}</lang>
}</syntaxhighlight>




Faster when computing length and lowercase only once per value ([[wp:Schwartzian transform|Schwartzian transform]]):
Faster when computing length and lowercase only once per value ([[wp:Schwartzian transform|Schwartzian transform]]):


<lang kotlin>fun main(args: Array<String>) {
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) {
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
println("Unsorted: $strings")
Line 2,594: Line 2,594:


println("Sorted: $sorted")
println("Sorted: $sorted")
}</lang>
}</syntaxhighlight>




Line 2,602: Line 2,602:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>test = { "Here", "we", "have", "some", "sample", "strings", "to", "be", "sorted" }
<syntaxhighlight lang="lua">test = { "Here", "we", "have", "some", "sample", "strings", "to", "be", "sorted" }


function stringSorter(a, b)
function stringSorter(a, b)
Line 2,613: Line 2,613:


-- print sorted table
-- print sorted table
for k,v in pairs(test) do print(v) end</lang>
for k,v in pairs(test) do print(v) end</syntaxhighlight>


{{out}}
{{out}}
Line 2,622: Line 2,622:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Class Quick {
Class Quick {
Line 2,702: Line 2,702:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


ForStringsSpecial can be coded using a Compare(aj$, lx$). See the use of break to break cases in select cases.
ForStringsSpecial can be coded using a Compare(aj$, lx$). See the use of break to break cases in select cases.
Any case in Select case may have one statement (if then is one statement), or a block of code. We can leave a case with a blank line after, a one statement line, or a block of code, or a case statement. A break statement break cases, so all code executed, until a continue found, to exit from Select (next statement after End Select). We use a sub to make two statements as one.
Any case in Select case may have one statement (if then is one statement), or a block of code. We can leave a case with a blank line after, a one statement line, or a block of code, or a case statement. A break statement break cases, so all code executed, until a continue found, to exit from Select (next statement after End Select). We use a sub to make two statements as one.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Group Quick {
Group Quick {
Module ForStringsSpecial {
Module ForStringsSpecial {
Line 2,736: Line 2,736:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,778: Line 2,778:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>Compare_fn:= proc(s1, s2)
<syntaxhighlight lang="maple">Compare_fn:= proc(s1, s2)
local len1, len2;
local len1, len2;
len1 := StringTools:-Length(s1);
len1 := StringTools:-Length(s1);
Line 2,792: Line 2,792:


L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted", "Tooo"];
L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted", "Tooo"];
sort(L, Compare_fn);</lang>
sort(L, Compare_fn);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,802: Line 2,802:
We define a new function to give true or false if two elements are in order.
We define a new function to give true or false if two elements are in order.
After that we can simply use the built-in Sort with an ordering function:
After that we can simply use the built-in Sort with an ordering function:
<lang Mathematica>StringOrderQ[x_String, y_String] :=
<syntaxhighlight lang="mathematica">StringOrderQ[x_String, y_String] :=
If[StringLength[x] == StringLength[y],
If[StringLength[x] == StringLength[y],
OrderedQ[{x, y}],
OrderedQ[{x, y}],
Line 2,808: Line 2,808:
]
]
words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"};
words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"};
Sort[words,StringOrderQ]</lang>
Sort[words,StringOrderQ]</syntaxhighlight>
gives back:
gives back:
<pre>{sambaa,sander,second,sifted,sorted,sunday,and,for,on,a}</pre>
<pre>{sambaa,sander,second,sifted,sorted,sunday,and,for,on,a}</pre>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>strangeorderp(a, b) := slength(a) > slength(b) or (slength(a) = slength(b) and orderlessp(a, b))$
<syntaxhighlight lang="maxima">strangeorderp(a, b) := slength(a) > slength(b) or (slength(a) = slength(b) and orderlessp(a, b))$
s: tokens("Lorem ipsum dolor sit amet consectetur adipiscing elit Sed non risus Suspendisse\
s: tokens("Lorem ipsum dolor sit amet consectetur adipiscing elit Sed non risus Suspendisse\
lectus tortor dignissim sit amet adipiscing nec ultricies sed dolor")$
lectus tortor dignissim sit amet adipiscing nec ultricies sed dolor")$
Line 2,820: Line 2,820:
["Suspendisse", "consectetur", "adipiscing", "adipiscing", "dignissim", "ultricies",
["Suspendisse", "consectetur", "adipiscing", "adipiscing", "dignissim", "ultricies",
"lectus", "tortor", "Lorem", "dolor", "dolor", "ipsum", "risus", "amet", "amet",
"lectus", "tortor", "Lorem", "dolor", "dolor", "ipsum", "risus", "amet", "amet",
"elit", "Sed", "nec", "non", "sed", "sit", "sit"]</lang>
"elit", "Sed", "nec", "non", "sed", "sit", "sit"]</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>fn myCmp str1 str2 =
<syntaxhighlight lang="maxscript">fn myCmp str1 str2 =
(
(
case of
case of
Line 2,845: Line 2,845:
strList = #("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
strList = #("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
qSort strList myCmp
qSort strList myCmp
print strList</lang>
print strList</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>("Here" "are" "some" "sample" "strings" "to" "be" "sorted")
<syntaxhighlight lang="min">("Here" "are" "some" "sample" "strings" "to" "be" "sorted")
(((length) (length)) spread <) sort print</lang>
(((length) (length)) spread <) sort print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,857: Line 2,857:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;


module CustomSort
module CustomSort
Line 2,869: Line 2,869:
WriteLine(strings2.Sort((x, y) => x.CompareTo(y)))
WriteLine(strings2.Sort((x, y) => x.CompareTo(y)))
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[different, strings, length, these, are, of]
<pre>[different, strings, length, these, are, of]
Line 2,876: Line 2,876:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,908: Line 2,908:
else signal IllegalArgumentException('Arguments must be Strings')
else signal IllegalArgumentException('Arguments must be Strings')
return cRes
return cRes
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,916: Line 2,916:


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>sort fork [=[tally first,tally last],up, >= [tally first,tally last]] ['Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted']
<syntaxhighlight lang="nial">sort fork [=[tally first,tally last],up, >= [tally first,tally last]] ['Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted']
=+-------+------+------+----+----+---+--+--+
=+-------+------+------+----+----+---+--+--+
=|strings|sample|sorted|Here|some|are|be|to|
=|strings|sample|sorted|Here|some|are|be|to|
=+-------+------+------+----+----+---+--+--+</lang>
=+-------+------+------+----+----+---+--+--+</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils, algorithm
<syntaxhighlight lang="nim">import strutils, algorithm


var strings = "here are Some sample strings to be sorted".split(' ')
var strings = "here are Some sample strings to be sorted".split(' ')
Line 2,932: Line 2,932:
)
)


echo strings</lang>
echo strings</syntaxhighlight>


{{out}}
{{out}}
Line 2,938: Line 2,938:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use Collection;
<syntaxhighlight lang="objeck">use Collection;


class Test {
class Test {
Line 2,994: Line 2,994:
return @s;
return @s;
}
}
}</lang>
}</syntaxhighlight>


<pre>
<pre>
Line 3,004: Line 3,004:
{{works with|Cocoa|Mac OS X 10.6+}}
{{works with|Cocoa|Mac OS X 10.6+}}
Using blocks:
Using blocks:
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


#define esign(X) (((X)>0)?1:(((X)<0)?-1:0))
#define esign(X) (((X)>0)?1:(((X)<0)?-1:0))
Line 3,031: Line 3,031:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>




Line 3,037: Line 3,037:


{{works with|Cocoa}}
{{works with|Cocoa}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface NSString (CustomComp)
@interface NSString (CustomComp)
Line 3,072: Line 3,072:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


This example can also be written using sort descriptors:
This example can also be written using sort descriptors:
{{works with|GNUstep}}
{{works with|GNUstep}}
{{works with|Cocoa}}
{{works with|Cocoa}}
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main()
int main()
Line 3,094: Line 3,094:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let mycmp s1 s2 =
<syntaxhighlight lang="ocaml">let mycmp s1 s2 =
if String.length s1 <> String.length s2 then
if String.length s1 <> String.length s2 then
compare (String.length s2) (String.length s1)
compare (String.length s2) (String.length s1)
else
else
String.compare (String.lowercase s1) (String.lowercase s2)</lang>
String.compare (String.lowercase s1) (String.lowercase s2)</syntaxhighlight>


List:
List:
<lang ocaml># let strings = ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"];;
<syntaxhighlight lang="ocaml"># let strings = ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"];;
val strings : string list =
val strings : string list =
["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"]
["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"]
# List.sort mycmp strings;;
# List.sort mycmp strings;;
- : string list =
- : string list =
["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"]</lang>
["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"]</syntaxhighlight>


Array:
Array:
<lang ocaml># let strings = [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|];;
<syntaxhighlight lang="ocaml"># let strings = [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|];;
val strings : string array =
val strings : string array =
[|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|]
[|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|]
Line 3,119: Line 3,119:
# strings;;
# strings;;
- : string array =
- : string array =
[|"strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"|]</lang>
[|"strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"|]</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>String method: customCmp(s)
<syntaxhighlight lang="oforth">String method: customCmp(s)
s size self size > ifTrue: [ true return ]
s size self size > ifTrue: [ true return ]
s size self size < ifTrue: [ false return ]
s size self size < ifTrue: [ false return ]
Line 3,129: Line 3,129:


["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]
["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]
sortWith(#customCmp) println</lang>
sortWith(#customCmp) println</syntaxhighlight>


{{out}}
{{out}}
Line 3,137: Line 3,137:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(import (scheme char))
(import (scheme char))


Line 3,154: Line 3,154:
"hendrerit" "viverra" "turpis" "ac" "sagittis"
"hendrerit" "viverra" "turpis" "ac" "sagittis"
"arcu" "pharetra" "id")))
"arcu" "pharetra" "id")))
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>A=.array~of('The seven deadly sins','Pride','avarice','Wrath','envy','gluttony','sloth','Lust')
<syntaxhighlight lang="oorexx">A=.array~of('The seven deadly sins','Pride','avarice','Wrath','envy','gluttony','sloth','Lust')
say 'Sorted in order of descending length, and in ascending lexicographic order'
say 'Sorted in order of descending length, and in ascending lexicographic order'
say A~sortWith(.DescLengthAscLexical~new)~makeString
say A~sortWith(.DescLengthAscLexical~new)~makeString
Line 3,166: Line 3,166:
if left~length==right~length
if left~length==right~length
then return left~caselessCompareTo(right)
then return left~caselessCompareTo(right)
else return right~length-left~length</lang>
else return right~length-left~length</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,181: Line 3,181:


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang>
<syntaxhighlight lang="text">
uses generics 'containing sort macros
uses generics 'containing sort macros
uses console
uses console
Line 3,216: Line 3,216:
next
next
pause
pause
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {LexicographicLessThan Xs Ys}
fun {LexicographicLessThan Xs Ys}
for
for
Line 3,239: Line 3,239:
Strings = ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]
Strings = ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]
in
in
{ForAll {Sort Strings LessThan} System.showInfo}</lang>
{ForAll {Sort Strings LessThan} System.showInfo}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>cmp(a,b)=if(#a<#b,1,if(#a>#b,-1,lex(a,b)));
<syntaxhighlight lang="parigp">cmp(a,b)=if(#a<#b,1,if(#a>#b,-1,lex(a,b)));
vecsort(v,cmp)</lang>
vecsort(v,cmp)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 3,250: Line 3,250:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use feature 'say';
<syntaxhighlight lang="perl">use feature 'say';


@strings = qw/Here are some sample strings to be sorted/;
@strings = qw/Here are some sample strings to be sorted/;
Line 3,265: Line 3,265:
sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] }
sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] }
map { [ $_, length, lc ] }
map { [ $_, length, lc ] }
@strings;</lang>
@strings;</syntaxhighlight>
{{out}}
{{out}}
<pre>strings sample sorted Here some are be to
<pre>strings sample sorted Here some are be to
Line 3,273: Line 3,273:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">my_compare</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;">function</span> <span style="color: #000000;">my_compare</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: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- descending length</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- descending length</span>
Line 3,282: Line 3,282:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">my_compare</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"Here"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"are"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"some"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"sample"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"strings"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"to"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"be"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"sorted"</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">my_compare</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"Here"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"are"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"some"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"sample"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"strings"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"to"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"be"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"sorted"</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,290: Line 3,290:
=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|4.4.4 CLI}}
{{works with|PHP|4.4.4 CLI}}
<lang php><?php
<syntaxhighlight lang="php"><?php
function mycmp($s1, $s2)
function mycmp($s1, $s2)
{
{
Line 3,300: Line 3,300:
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
usort($strings, "mycmp");
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Line 3,306: Line 3,306:
PicoLisp returns an ascending list (of any type). To get a result in descending
PicoLisp returns an ascending list (of any type). To get a result in descending
order, the "greater than" function can be supplied
order, the "greater than" function can be supplied
<lang PicoLisp>: (sort '("def" "abc" "ghi") >)
<syntaxhighlight lang="picolisp">: (sort '("def" "abc" "ghi") >)
-> ("ghi" "def" "abc")</lang>
-> ("ghi" "def" "abc")</syntaxhighlight>
or simply the result reversed (which is, btw, the most efficient way)
or simply the result reversed (which is, btw, the most efficient way)
<lang PicoLisp>: (flip (sort '("def" "abc" "ghi")))
<syntaxhighlight lang="picolisp">: (flip (sort '("def" "abc" "ghi")))
-> ("ghi" "def" "abc")</lang>
-> ("ghi" "def" "abc")</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
Line 3,316: Line 3,316:


'''Platform:''' [[WIN]]
'''Platform:''' [[WIN]]
<lang pli>MRGEPKG: package exports(MERGESORT,MERGE,RMERGE);
<syntaxhighlight lang="pli">MRGEPKG: package exports(MERGESORT,MERGE,RMERGE);


DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */
DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */
Line 3,385: Line 3,385:


put skip;
put skip;
END RMERGE;</lang>
END RMERGE;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>lvars ls = ['Here' 'are' 'some' 'sample' 'strings' 'to' 'be' 'sorted'];
<syntaxhighlight lang="pop11">lvars ls = ['Here' 'are' 'some' 'sample' 'strings' 'to' 'be' 'sorted'];
define compare(s1, s2);
define compare(s1, s2);
lvars k = length(s2) - length(s1);
lvars k = length(s2) - length(s1);
Line 3,408: Line 3,408:
l2 = length(s2);
l2 = length(s2);
l1 > l2 or (l1 == l2 and alphabefore(uppertolower(s1), uppertolower(s2)))
l1 > l2 or (l1 == l2 and alphabefore(uppertolower(s1), uppertolower(s2)))
enddefine;</lang>
enddefine;</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Line 3,414: Line 3,414:
{{works with|PB/CC|4}}
{{works with|PB/CC|4}}


<lang powerbasic>FUNCTION Sorter(p1 AS STRING, p2 AS STRING) AS LONG
<syntaxhighlight lang="powerbasic">FUNCTION Sorter(p1 AS STRING, p2 AS STRING) AS LONG
'if p1 should be first, returns -1
'if p1 should be first, returns -1
'if p2 should be first, returns 1
'if p2 should be first, returns 1
Line 3,439: Line 3,439:
'pb's built-in sorting; "USING" tells it to use our custom comparator
'pb's built-in sorting; "USING" tells it to use our custom comparator
ARRAY SORT x(), USING Sorter()
ARRAY SORT x(), USING Sorter()
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
The <code>Sort-Object</code> cmdlet accepts script blocks as arguments as well as multiple criteria after which to sort.
The <code>Sort-Object</code> cmdlet accepts script blocks as arguments as well as multiple criteria after which to sort.
<lang powershell>$list = "Here", "are", "some", "sample", "strings", "to", "be", "sorted"
<syntaxhighlight lang="powershell">$list = "Here", "are", "some", "sample", "strings", "to", "be", "sorted"
$list | Sort-Object {-$_.Length},{$_}</lang>
$list | Sort-Object {-$_.Length},{$_}</syntaxhighlight>
The negated string length is the first sort criterion, the second is the string itself, resulting in descending length and ascending lexicographic order.
The negated string length is the first sort criterion, the second is the string itself, resulting in descending length and ascending lexicographic order.


=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog (Tested on Version 8.1.19). Duplicates (if any) are removed.
Works with SWI-Prolog (Tested on Version 8.1.19). Duplicates (if any) are removed.
<lang Prolog>rosetta_sort :-
<syntaxhighlight lang="prolog">rosetta_sort :-
L = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted" ],
L = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted" ],
predsort(my_comp, L, L1),
predsort(my_comp, L, L1),
Line 3,467: Line 3,467:
my_write(W) :-
my_write(W) :-
format('~s ', [W]).
format('~s ', [W]).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,481: Line 3,481:
=={{header|Python}}==
=={{header|Python}}==
Using a key function is usually more efficient than a comparator. We can take advantage of the fact that tuples are ordered first by the first element, then by the second, etc., to perform a sort on multiple criteria.
Using a key function is usually more efficient than a comparator. We can take advantage of the fact that tuples are ordered first by the first element, then by the second, etc., to perform a sort on multiple criteria.
<lang python>strings = "here are Some sample strings to be sorted".split()
<syntaxhighlight lang="python">strings = "here are Some sample strings to be sorted".split()


def mykey(x):
def mykey(x):
return -len(x), x.upper()
return -len(x), x.upper()


print sorted(strings, key=mykey)</lang>
print sorted(strings, key=mykey)</syntaxhighlight>


{{out}}
{{out}}
<lang python>['strings', 'sample', 'sorted', 'here', 'Some', 'are', 'be', 'to']</lang>
<syntaxhighlight lang="python">['strings', 'sample', 'sorted', 'here', 'Some', 'are', 'be', 'to']</syntaxhighlight>


===Alternative method using cmp===
===Alternative method using cmp===
To technically comply with this task, we can also use an actual comparator (''cmp'') function which will be called every time members of the original list are to be compared. Note that this feature is worse than using the key argument and has been removed from Python 3, so should no longer be used in new code.
To technically comply with this task, we can also use an actual comparator (''cmp'') function which will be called every time members of the original list are to be compared. Note that this feature is worse than using the key argument and has been removed from Python 3, so should no longer be used in new code.
<lang python>def mycmp(s1, s2):
<syntaxhighlight lang="python">def mycmp(s1, s2):
return cmp(len(s2), len(s1)) or cmp(s1.upper(), s2.upper())
return cmp(len(s2), len(s1)) or cmp(s1.upper(), s2.upper())


print sorted(strings, cmp=mycmp)</lang>
print sorted(strings, cmp=mycmp)</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ $ "" swap
<syntaxhighlight lang="quackery"> [ $ "" swap
witheach
witheach
[ upper join ] ] is upper$ ( $ --> )
[ upper join ] ] is upper$ ( $ --> )
Line 3,517: Line 3,517:
$ "sharna pax and hed on a poal when the ardship of Cambry come out of his hoal"
$ "sharna pax and hed on a poal when the ardship of Cambry come out of his hoal"
nest$ sortwith comparator
nest$ sortwith comparator
witheach [ echo$ sp ]</lang>
witheach [ echo$ sp ]</syntaxhighlight>


{{out}}
{{out}}
Line 3,527: Line 3,527:
=={{header|R}}==
=={{header|R}}==


<lang R>v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
<syntaxhighlight lang="r">v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
print(v[order(-nchar(v), tolower(v))])</lang>
print(v[order(-nchar(v), tolower(v))])</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 3,548: Line 3,548:
(sort2 '("Some" "pile" "of" "words"))
(sort2 '("Some" "pile" "of" "words"))
;; -> '("words" "pile" "Some" "of")
;; -> '("words" "pile" "Some" "of")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)<br>
(formerly Perl 6)<br>
Primary sort by length of string, then break ties by sorting alphabetically (ignoring case).
Primary sort by length of string, then break ties by sorting alphabetically (ignoring case).
<lang perl6>my @strings = <Here are some sample strings to be sorted>;
<syntaxhighlight lang="raku" line>my @strings = <Here are some sample strings to be sorted>;
put @strings.sort:{.chars, .lc};
put @strings.sort:{.chars, .lc};
put sort -> $x { $x.chars, $x.lc }, @strings;</lang>
put sort -> $x { $x.chars, $x.lc }, @strings;</syntaxhighlight>
{{out}}
{{out}}
<pre>be to are Here some sample sorted strings
<pre>be to are Here some sample sorted strings
Line 3,562: Line 3,562:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program sorts a (stemmed) array using the merge-sort method. */
<syntaxhighlight lang="rexx">/*REXX program sorts a (stemmed) array using the merge-sort method. */
/* using mycmp function for the sort order */
/* using mycmp function for the sort order */
/**********************************************************************
/**********************************************************************
Line 3,691: Line 3,691:
Otherwise res=0
Otherwise res=0
End
End
RETURN res</lang>
RETURN res</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,717: Line 3,717:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"


Line 3,752: Line 3,752:
see oList[n] [1] + nl
see oList[n] [1] + nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,768: Line 3,768:
Since Ruby 1.8.6 Enumerables have a "sort_by" method, taking a key block, which is more efficient than a comparator. We can take advantage of the fact that Arrays are ordered first by the first element, then by the second, etc., to perform a sort on multiple criteria.
Since Ruby 1.8.6 Enumerables have a "sort_by" method, taking a key block, which is more efficient than a comparator. We can take advantage of the fact that Arrays are ordered first by the first element, then by the second, etc., to perform a sort on multiple criteria.


<lang ruby>words = %w(Here are some sample strings to be sorted)
<syntaxhighlight lang="ruby">words = %w(Here are some sample strings to be sorted)
p words.sort_by {|word| [-word.size, word.downcase]}</lang>
p words.sort_by {|word| [-word.size, word.downcase]}</syntaxhighlight>


To technically comply with this task, we can also use an actual comparator block which will be called every time members of the original list are to be compared.
To technically comply with this task, we can also use an actual comparator block which will be called every time members of the original list are to be compared.
<lang ruby>p words.sort {|a, b| d = b.size <=> a.size
<syntaxhighlight lang="ruby">p words.sort {|a, b| d = b.size <=> a.size
d != 0 ? d : a.upcase <=> b.upcase}</lang>
d != 0 ? d : a.upcase <=> b.upcase}</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
fn main() {
fn main() {
let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
Line 3,782: Line 3,782:
println!("{:?}", words);
println!("{:?}", words);
}
}
</syntaxhighlight>
</lang>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is


custom_comp(a, b:STR):BOOL is
custom_comp(a, b:STR):BOOL is
Line 3,799: Line 3,799:
loop #OUT + s.elt! + "\n"; end;
loop #OUT + s.elt! + "\n"; end;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) =>
<syntaxhighlight lang="scala">List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) =>
val cmp=a.size-b.size
val cmp=a.size-b.size
(if (cmp==0) -a.compareTo(b) else cmp) > 0
(if (cmp==0) -a.compareTo(b) else cmp) > 0
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>List(strings, sample, sorted, Here, some, are, be, to)</pre>
<pre>List(strings, sample, sorted, Here, some, are, be, to)</pre>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(use srfi-13);;Syntax for module inclusion depends on implementation,
<syntaxhighlight lang="scheme">(use srfi-13);;Syntax for module inclusion depends on implementation,
;;a sort function may be predefined, or available through srfi 95
;;a sort function may be predefined, or available through srfi 95
(define (mypred? a b)
(define (mypred? a b)
Line 3,819: Line 3,819:
(> len-a len-b))))
(> len-a len-b))))


(sort '("sorted" "here" "strings" "sample" "Some" "are" "be" "to") mypred?) </lang>
(sort '("sorted" "here" "strings" "sample" "Some" "are" "be" "to") mypred?) </syntaxhighlight>
{{out}}
{{out}}
<lang scheme>("strings" "sample" "sorted" "here" "Some" "are" "be" "to")</lang>
<syntaxhighlight lang="scheme">("strings" "sample" "sorted" "here" "Some" "are" "be" "to")</syntaxhighlight>




Line 3,827: Line 3,827:
{{works with|Gauche Scheme}}
{{works with|Gauche Scheme}}


<lang Scheme>(define strings '(
<syntaxhighlight lang="scheme">(define strings '(
"This" "Is" "A" "Set" "Of" "Strings" "To" "Sort" "duplicated"
"This" "Is" "A" "Set" "Of" "Strings" "To" "Sort" "duplicated"
"this" "is" "a" "set" "of" "strings" "to" "sort" "duplicated"))
"this" "is" "a" "set" "of" "strings" "to" "sort" "duplicated"))
Line 3,838: Line 3,838:
(apply string-ci<? two)
(apply string-ci<? two)
(apply > sizes)))))
(apply > sizes)))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,846: Line 3,846:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func mycmp(a, b) { (b.len <=> a.len) || (a.lc <=> b.lc) };
<syntaxhighlight lang="ruby">func mycmp(a, b) { (b.len <=> a.len) || (a.lc <=> b.lc) };
var strings = %w(Here are some sample strings to be sorted);
var strings = %w(Here are some sample strings to be sorted);
var sorted = strings.sort(mycmp);</lang>
var sorted = strings.sort(mycmp);</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)').
<syntaxhighlight lang="slate">define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)').
words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]</lang>
words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>#('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)' ) asSortedCollection
<syntaxhighlight lang="smalltalk">#('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)' ) asSortedCollection
sortBlock:
sortBlock:
[:first :second | (second size = first size)
[:first :second | (second size = first size)
ifFalse: [second size < first size]
ifFalse: [second size < first size]
ifTrue: [first < second]]</lang>
ifTrue: [first < second]]</syntaxhighlight>
the above creates a sorted collection;
the above creates a sorted collection;
an inplace sort of arrayed collections is done with eg.:
an inplace sort of arrayed collections is done with eg.:
<lang smalltalk>#('here' 'are' 'some' 'sample' 'strings')
<syntaxhighlight lang="smalltalk">#('here' 'are' 'some' 'sample' 'strings')
sort:[:a :b | a reversed < b reversed]</lang>
sort:[:a :b | a reversed < b reversed]</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
List:
List:
{{works with|SML/NJ}}
{{works with|SML/NJ}}
<lang sml>fun mygt (s1, s2) =
<syntaxhighlight lang="sml">fun mygt (s1, s2) =
if size s1 <> size s2 then
if size s1 <> size s2 then
size s2 > size s1
size s2 > size s1
else
else
String.map Char.toLower s1 > String.map Char.toLower s2</lang>
String.map Char.toLower s1 > String.map Char.toLower s2</syntaxhighlight>


<lang sml>- val strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
<syntaxhighlight lang="sml">- val strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
val strings = ["Here","are","some","sample","strings","to","be","sorted"]
val strings = ["Here","are","some","sample","strings","to","be","sorted"]
: string list
: string list
- ListMergeSort.sort mygt strings;
- ListMergeSort.sort mygt strings;
val it = ["strings","sample","sorted","Here","some","are","be","to"]
val it = ["strings","sample","sorted","Here","some","are","be","to"]
: string list</lang>
: string list</syntaxhighlight>


Array:
Array:
{{works with|SML/NJ}}
{{works with|SML/NJ}}
<lang sml>fun mycmp (s1, s2) =
<syntaxhighlight lang="sml">fun mycmp (s1, s2) =
if size s1 <> size s2 then
if size s1 <> size s2 then
Int.compare (size s2, size s1)
Int.compare (size s2, size s1)
else
else
String.compare (String.map Char.toLower s1, String.map Char.toLower s2)</lang>
String.compare (String.map Char.toLower s1, String.map Char.toLower s2)</syntaxhighlight>


<lang sml>- val strings = Array.fromList ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
<syntaxhighlight lang="sml">- val strings = Array.fromList ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
val strings = [|"Here","are","some","sample","strings","to","be","sorted"|]
val strings = [|"Here","are","some","sample","strings","to","be","sorted"|]
: string array
: string array
Line 3,896: Line 3,896:
- strings;
- strings;
val it = [|"strings","sample","sorted","Here","some","are","be","to"|]
val it = [|"strings","sample","sorted","Here","some","are","be","to"|]
: string array</lang>
: string array</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


var list = ["this",
var list = ["this",
Line 3,929: Line 3,929:
return lhsCount > rhsCount
return lhsCount > rhsCount
}</lang>
}</syntaxhighlight>
{{works with|Swift|1.2}}
{{works with|Swift|1.2}}
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


var list = ["this",
var list = ["this",
Line 3,960: Line 3,960:
return lhsCount > rhsCount
return lhsCount > rhsCount
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc sorter {a b} {
<syntaxhighlight lang="tcl">proc sorter {a b} {
set la [string length $a]
set la [string length $a]
set lb [string length $b]
set lb [string length $b]
Line 3,975: Line 3,975:


set strings {here are Some sample strings to be sorted}
set strings {here are Some sample strings to be sorted}
lsort -command sorter $strings ;# ==> strings sample sorted here Some are be to</lang>
lsort -command sorter $strings ;# ==> strings sample sorted here Some are be to</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort"
setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort"
Line 3,992: Line 3,992:
PRINT "2. setofstrings sorted"
PRINT "2. setofstrings sorted"
*{sorted}
*{sorted}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style='height:30ex;overflow:scroll'>
<pre style='height:30ex;overflow:scroll'>
Line 4,035: Line 4,035:
The less or equal length predicate (leql) and lexically less or equal predicate (lleq) are also standard library functions. This task is therefore easily dispatched as shown.
The less or equal length predicate (leql) and lexically less or equal predicate (lleq) are also standard library functions. This task is therefore easily dispatched as shown.


<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#show+
#show+


data = <'this','is','a','list','of','strings','to','be','sorted'>
data = <'this','is','a','list','of','strings','to','be','sorted'>


example = psort<not leql,lleq+ ~* ~&K31K30piK26 letters> data</lang>
example = psort<not leql,lleq+ ~* ~&K31K30piK26 letters> data</syntaxhighlight>
The lleq library function is case sensitive, so it is composed with a function to convert the words to lower case on the fly (without destructively modifying them) in order to meet the task requirement of case insensitivity.
The lleq library function is case sensitive, so it is composed with a function to convert the words to lower case on the fly (without destructively modifying them) in order to meet the task requirement of case insensitivity.


Line 4,056: Line 4,056:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==


<lang vbnet>Imports System
<syntaxhighlight lang="vbnet">Imports System


Module Sorting_Using_a_Custom_Comparator
Module Sorting_Using_a_Custom_Comparator
Line 4,073: Line 4,073:
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-sort}}
<lang ecmascript>import "/sort" for Cmp, Sort
<syntaxhighlight lang="ecmascript">import "/sort" for Cmp, Sort


var cmp = Fn.new { |s, t|
var cmp = Fn.new { |s, t|
Line 4,088: Line 4,088:
System.print("Unsorted: %(strings)")
System.print("Unsorted: %(strings)")
Sort.insertion(strings, cmp)
Sort.insertion(strings, cmp)
System.print("Sorted : %(strings)")</lang>
System.print("Sorted : %(strings)")</syntaxhighlight>


{{out}}
{{out}}
Line 4,097: Line 4,097:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>s:=T("Cat","apple","Adam","zero","Xmas","quit","Level","add","Actor","base","butter");
<syntaxhighlight lang="zkl">s:=T("Cat","apple","Adam","zero","Xmas","quit","Level","add","Actor","base","butter");
r:=s.sort(fcn(a,b){
r:=s.sort(fcn(a,b){
an,bn := a.len(),b.len();
an,bn := a.len(),b.len();
if(an==bn)(a.toLower() < b.toLower()) else (an > bn)
if(an==bn)(a.toLower() < b.toLower()) else (an > bn)
});
});
r.pump(Console.println);</lang>
r.pump(Console.println);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>