Sort using a custom comparator: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Wren}}: Minor tidy) |
|||
(14 intermediate revisions by 11 users not shown) | |||
Line 15:
{{trans|Python}}
<
print(sorted(strings, key' x -> (-x.len, x.uppercase())))</
{{out}}
Line 26:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program customSort64.s */
Line 384:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Name : London country : UK
Line 411:
=={{header|Action!}}==
<
PROC PrintArray(PTR ARRAY a INT size)
Line 488:
Test(a,24,CustomComparator)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_using_a_custom_comparator.png Screenshot from Atari 8-bit computer]
Line 506:
{{incorrect}}
{{works with|GNAT|}}
<
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
Line 614:
Put_Line("Sorted list:");
Put(Strings);
end Custom_Compare;</
{{out}}
<pre>Unsorted list:
Line 655:
{{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.
<
MODE SITEM = STRING;
#--- Swap function ---#
Line 748:
quicksort(a, compare);
print(("After :"));FOR i FROM LWB a TO UPB a DO print((" ",a[i])) OD; print((newline))
)</
{{out}}
<pre>
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:
<
-- SORTING LISTS OF ATOMIC (NON-RECORD) DATA WITH A CUSTOM SORT FUNCTION
Line 855:
sortBy(lengthDownAZup, xs)
end run</
{{Out}}
<pre>{"Sao Paulo", "Shanghai", "Beijing", "Karachi", "Delhi", "Dhaka", "Lagos"}</pre>
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>:
<
use framework "Foundation"
Line 873:
tell arrayOfStrings to sortUsingDescriptors:({descendingByLength, ascendingLexicographically})
return arrayOfStrings as list</
{{output}}
Line 879:
===Vanilla===
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
use sorter : script ¬
"Custom Iterative Ternary Merge Sort" --<www.macscripter.net/t/timsort-and-nigsort/71383/3>
-- Sort customiser.
script descendingByLengthThenAscendingLexicographically
on isGreater(a, b)
set lenA to
set lenB to
if (lenA = lenB) then return (a > b)
end isGreater
end script
set listOfText to words of "now is the time for all good men to come to the aid of the party"
tell sorter to ¬
sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
return listOfText</syntaxhighlight>
{{output}}
<pre>{"party", "come", "good", "time", "aid", "all", "for", "men", "now", "the", "the", "the", "is", "of", "to", "to"}</pre>
=={{header|ATS}}==
<syntaxhighlight lang="ats">(* The following demonstrates a few ways to customize the
comparator. *)
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
%{^
#include <strings.h>
%}
extern fn
strcasecmp : (string, string) -<> int = "mac#strcasecmp"
fn
sort_strings_1 (lst : List string,
cmp : (string, string) -<> int)
:<!wrt> List string =
list_vt2t (list_mergesort_fun<string> (lst, cmp))
fn
sort_strings_2 (lst : List string,
cmp : (string, string) -<cloref> int)
:<!wrt> List string =
list_vt2t (list_mergesort_cloref<string> (lst, cmp))
fn
sort_using_a_template_function (lst : List string)
:<!wrt> List string =
(* There is no actual callback here. The comparison code is expanded
directly into the sort code. *)
let
implement
list_mergesort$cmp<string> (x, y) =
let
val m = length x
and n = length y
in
if m < n then
1
else if n < m then
~1
else
strcasecmp (x, y)
end
in
(* The list mergesort template functions in the ATS prelude return
_linear_ lists. Thus the call to list_vt2t to cast that result
to an ordinary list. *)
list_vt2t (list_mergesort<string> lst)
end
fn
sort_using_an_ordinary_function (lst : List string)
:<!wrt> List string =
(* Rather than expand the comparison code, incorporate a function
call into the sort implementation. *)
let
fn
cmp (x : string,
y : string)
:<> int =
let
val m = length x
and n = length y
in
if m < n then
1
else if n < m then
~1
else
strcasecmp (x, y)
end
in
list_vt2t (list_mergesort_fun<string> (lst, cmp))
end
fn
sort_the_way_it_works_for_qsort_in_C (lst : List string)
:<!wrt> List string =
(* Here we have a true callback to an ordinary function. *)
let
fn
cmp (x : string,
y : string)
:<> int =
let
val m = length x
and n = length y
in
if m < n then
1
else if n < m then
~1
else
strcasecmp (x, y)
end
in
sort_strings_1 (lst, cmp)
end
fn
sort_using_a_closure (lst : List string)
:<!wrt> List string =
(* Incorporate a closure into the sort implementation. (Standard C
does not have closures.) *)
let
fn
cmp (x : string,
y : string)
:<cloref> int =
let
val m = length x
and n = length y
in
if m < n then
1
else if n < m then
~1
else
strcasecmp (x, y)
end
in
list_vt2t (list_mergesort_cloref<string> (lst, cmp))
end
fn
sort_by_calling_back_to_a_closure (lst : List string)
:<!wrt> List string =
let
fn
cmp (x : string,
y : string)
:<cloref> int =
let
val m = length x
and n = length y
in
if m < n then
1
else if n < m then
~1
else
strcasecmp (x, y)
end
in
sort_strings_2 (lst, cmp)
end
implement
main0 () =
let
val unsorted =
$list{string}
("Here", "are", "some", "sample", "strings",
"to", "be", "sorted")
val sorted1 = sort_using_a_template_function unsorted
val sorted2 = sort_using_an_ordinary_function unsorted
val sorted3 = sort_the_way_it_works_for_qsort_in_C unsorted
val sorted4 = sort_using_a_closure unsorted
val sorted5 = sort_by_calling_back_to_a_closure unsorted
in
println! unsorted;
println! sorted1;
println! sorted2;
println! sorted3;
println! sorted4;
println! sorted5
end</syntaxhighlight>
{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW -O3 sort_using_custom_comparator.dats -lgc && ./a.out
Here, are, some, sample, strings, to, be, sorted
strings, sample, sorted, Here, some, are, be, to
strings, sample, sorted, Here, some, are, be, to
strings, sample, sorted, Here, some, are, be, to
strings, sample, sorted, Here, some, are, be, to
strings, sample, sorted, Here, some, are, be, to</pre>
=={{header|AutoHotkey}}==
<
strings = Here,are,some,sample,strings,to,be,sorted
Sort, numbers, F IntegerSort D,
Line 920 ⟶ 1,096:
StringLengthSort(a1, a2){
return strlen(a1) - strlen(a2)
}</
=={{header|AWK}}==
For GAWK, this uses the inbuilt descending numeric ordering and a custom comparison routine for caseless string comparison.
May need modification for TAWK.
<
#
# sorting:
Line 957 ⟶ 1,133:
l2 = tolower( i2 );
return ( ( l1 < l2 ) ? -1 : ( ( l1 == l2 ) ? 0 : 1 ) );
} # caselessCompare</
{{out}}
<pre>
Line 1,005 ⟶ 1,181:
To sort ASCII strings, use the strsort or lexsort utilities to sort alphabetically and lexicographically, respectively.
<
( "Here" "are" "be" "sample" "some" "sorted" "strings" "to" )
babel> ("Here" "are" "some" "sample" "strings" "to" "be" "sorted") lexsort ! lsstr !
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</
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:
<
( "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 !
( "be" "to" "are" "Here" "some" "sample" "sorted" "strings" )</
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:
<
( 3 4 4 5 5 6 8 9 9 9 )</
You can even shuffle a list with lssort using the randlf operator (your results will probably differ):
<
( 7 5 9 6 2 4 3 1 8 )</
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:
<
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
Line 1,053 ⟶ 1,229:
( 15 13 )
( 17 3 )
( 18 9 )</
=={{header|Burlesque}}==
<
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}><
{"ADD" "Abc" "Acb" "acb" "acc"}
blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb
{"Abc" "acb" "Acb" "acc" "ADD"}
</syntaxhighlight>
=={{header|C}}==
{{works with|POSIX|.1-2001}}
<
#include <string.h> /* for strlen */
#include <strings.h> /* for strcasecmp */
Line 1,088 ⟶ 1,264:
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}</
=={{header|C sharp|C#}}==
Line 1,098 ⟶ 1,274:
C# allows you to specify a custom compare to the built in sort method on a list
<
using System.Collections.Generic;
Line 1,137 ⟶ 1,313:
}
}
}</
{{out}}
Line 1,179 ⟶ 1,355:
<
using System.Collections.Generic;
using System.Linq;
Line 1,218 ⟶ 1,394:
}
}
</syntaxhighlight>
=={{header|C++}}==
{{works with|g++|4.1.2}}
<
#include <string>
#include <cctype>
Line 1,250 ⟶ 1,426:
std::sort(strings, strings+8, compare());
return 0;
}</
=={{header|Ceylon}}==
<
value strings = [
Line 1,266 ⟶ 1,442:
sorted.each(print);
}</
=={{header|Clean}}==
<
less s1 s2
Line 1,279 ⟶ 1,455:
lower s = {toLower c \\ c <-: s}
Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"]</
=={{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.
<
(let [len1 (count s1), len2 (count s2)]
(if (= len1 len2)
Line 1,291 ⟶ 1,467:
(println
(sort rosetta-compare
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]))</
{{out}}
Line 1,299 ⟶ 1,475:
An alternative, using <tt>sort-by</tt>:
<
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"])</
=={{header|Common Lisp}}==
Line 1,307 ⟶ 1,483:
For example, to sort strings case-insensitively in ascending order:
<
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
*STRINGS*
CL-USER> (sort *strings* #'string-lessp)
("Actor" "Adam" "add" "apple" "base" "butter" "Cat" "Level" "quit" "Xmas"
"zero")</
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:
<
(list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter"))
*STRINGS*
CL-USER> (sort *strings* #'> :key #'length)
("butter" "apple" "Level" "Actor" "Adam" "zero" "Xmas" "quit" "base"
"Cat" "add")</
=={{header|D}}==
<
void main() {
Line 1,331 ⟶ 1,507:
.schwartzSort!q{ tuple(-a.length, a.toUpper) }
.writeln;
}</
{{out}}
<pre>["strings", "sample", "sorted", "here", "Some", "are", "be", "to"]</pre>
Line 1,338 ⟶ 1,514:
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):
<
import std.stdio, std.string, std.algorithm;
Line 1,344 ⟶ 1,520:
parts.multiSort!(q{a.length > b.length}, q{a.toUpper < b.toUpper});
parts.writeln;
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,367 ⟶ 1,543:
Result := CompareText(Left, Right);
end));
end.</
=={{header|E}}==
<
def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } }
Line 1,377 ⟶ 1,553:
nonzeroOr(b.size().op__cmp(a.size()),
fn { a.compareToIgnoreCase(b) })
})</
=={{header|EGL}}==
{{works with|EDT|}}
<
function main()
Line 1,418 ⟶ 1,594:
end
end</
{{out}}
Line 1,445 ⟶ 1,621:
=={{header|Elena}}==
ELENA
<
import system'routines;
import system'culture;
Line 1,457 ⟶ 1,633:
console.printLine("Descending length: ", items.clone()
.sort::(p,n => p.Length > n.Length).asEnumerable());
console.printLine("Ascending order: ", items.clone()
.sort::(p,n => p.toUpper(invariantLocale) < n.toUpper(invariantLocale)).asEnumerable())
}</
{{out}}
<pre>
Line 1,470 ⟶ 1,646:
=={{header|Elixir}}==
<
comparator = fn s1,s2 -> if String.length(s1)==String.length(s2),
Line 1,478 ⟶ 1,654:
# or
IO.inspect Enum.sort_by(strs, fn str -> {-String.length(str), String.downcase(str)} end)</
{{out}}
Line 1,487 ⟶ 1,663:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( sort_using_custom_comparator ).
Line 1,500 ⟶ 1,676:
longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =< erlang:length(String2) -> false;
longest_first_case_insensitive( _String1, _String2 ) -> true.
</syntaxhighlight>
{{out}}
<pre>
Line 1,509 ⟶ 1,685:
=={{header|Euphoria}}==
<
include wildcard.e
include misc.e
Line 1,528 ⟶ 1,704:
puts(1,"\n\nSorted:\n")
pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2})</
{{out}}
Line 1,556 ⟶ 1,732:
=={{header|F_Sharp|F#}}==
<
match compare s2.Length s1.Length with
| 0 -> compare (s1.ToLower()) (s2.ToLower())
Line 1,565 ⟶ 1,741:
let sortedStrings = List.sortWith myCompare strings
printfn "%A" sortedStrings</
{{out}}
Line 1,571 ⟶ 1,747:
=={{header|Factor}}==
<
2dup [ length ] compare invert-comparison
dup +eq+ = [ drop [ >lower ] compare ] [ 2nip ] if ;
{ "this" "is" "a" "set" "of" "strings" "to" "sort" } [ my-compare ] sort</
=={{header|Fantom}}==
Line 1,581 ⟶ 1,757:
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.
<
class Main
{
Line 1,602 ⟶ 1,778:
}
}
</syntaxhighlight>
{{out}}
Line 1,615 ⟶ 1,791:
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.
<
implicit none
contains
Line 1,647 ⟶ 1,823:
end do
end subroutine a_sort
end module sorts_with_custom_comparator</
Then we have to put our custom comparator in a module (<tt>to_lower</tt> is defined [[Change string case|here]]):
<
implicit none
contains
Line 1,676 ⟶ 1,852:
end if
end function my_compare
end module comparators</
At the end, we can test these:
<
use comparators
use sorts_with_custom_comparator
Line 1,694 ⟶ 1,870:
print *, trim(str(i))
end do
end program CustomComparator</
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,744 ⟶ 1,920:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>strings
Line 1,757 ⟶ 1,933:
=={{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!
<
len = length[b] <=> length[a]
if len != 0
Line 1,766 ⟶ 1,942:
words = split[%r/\s+/, "Here are some sample strings to be sorted"]
println[sort[words, f]]</
{{out}}
<pre>
Line 1,773 ⟶ 1,949:
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.
<
words = ["Ærø", "Aalborg", "Tårnby", "Vejen", "Thisted", "Stevns", "Sønderborg", "Eliasen"]
println[sort[words, f, "da"]]</
{{out}}
<pre>
Line 1,785 ⟶ 1,961:
=={{header|FunL}}==
<
println( ["here", "are", "Some", "sample", "strings", "to", "be", "sorted"].sortWith(preceeds) )</
{{out}}
Line 1,794 ⟶ 1,970:
["strings", "sample", "sorted", "here", "Some", "are", "be", "to"]
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
local fn CustomComparator( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
NSComparisonResult result = fn StringCaseInsensitiveCompare( obj1, obj2 )
end fn = result
local fn ComparatorStringSort( wordString as CFStringRef ) as CFStringRef
CFArrayRef stringArray = fn StringComponentsSeparatedByString( wordString, @" " )
CFArrayRef sortedArray = fn ArraySortedArrayUsingFunction( stringArray, @fn CustomComparator, NULL )
CFStringRef sortedStr = fn ArrayComponentsJoinedByString( sortedArray, @"\n" )
end fn = sortedStr
NSLog( @"%@", fn ComparatorStringSort( @"The quick brown fox jumped over the lazy dog's back" ) )
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
back
brown
dog's
fox
jumped
lazy
over
quick
The
the
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_using_a_custom_comparator}}
'''Solution'''
[[File:Fōrmulæ - Sort using a custom comparator 01.png]]
[[File:Fōrmulæ - Sort using a custom comparator 02.png]]
=={{header|Go}}==
<
import (
Line 1,830 ⟶ 2,045:
sort.Sort(s)
fmt.Println(s, "(sorted)")
}</
{{out}}
<pre>[To tell your name the livelong day To an admiring bog] (original)
Line 1,837 ⟶ 2,052:
=={{header|Groovy}}==
The "custom comparator" is just a closure attached to the sort method invocation.
<
strings.sort { x, y ->
y.length() <=> x.length() ?: x.compareToIgnoreCase(y)
}
println strings</
{{out}}
Line 1,848 ⟶ 2,063:
=={{header|Haskell}}==
{{works with|GHC}}
<
import Data.List (sortBy)
import Data.Ord (comparing)
Line 1,881 ⟶ 2,096:
]
)
)</
{{Out}}
<pre>be
Line 1,902 ⟶ 2,117:
=={{header|Icon}} and {{header|Unicon}}==
<
write("Sorting Demo for custom comparator")
L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
Line 1,914 ⟶ 2,129:
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
end</
Note(1): This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]].
Line 1,947 ⟶ 2,162:
Standard utilities <tt>tolower</tt> or <tt>toupper</tt> may be substituted.
<
length_and_lex =: (-@:# ; lower)&>
strings=: 'Here';'are';'some';'sample';'strings';'to';'be';'sorted'
Line 1,953 ⟶ 2,168:
+-------+------+------+----+----+---+--+--+
|strings|sample|sorted|Here|some|are|be|to|
+-------+------+------+----+----+---+--+--+</
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).
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.util.Arrays;
Line 1,976 ⟶ 2,193:
System.out.print(s + " ");
}
}</
Same thing as above
{{works with|Java|8+}}
<
import java.util.Arrays;
Line 1,997 ⟶ 2,214:
System.out.print(s + " ");
}
}</
Using Java 11
<syntaxhighlight lang="java">
import java.util.Comparator;
import java.util.List;
public final class SortUsingCustomComparator {
public static void main(String[] args) {
List<String> list = List.of( "Here", "are", "some", "sample", "strings", "to", "be", "sorted" );
Comparator<String> custom = Comparator.comparing(String::length, Comparator.reverseOrder())
.thenComparing(Comparator.naturalOrder());
List<String> sortedList = list.stream().sorted(custom).toList();
System.out.println(sortedList);
}
}
</syntaxhighlight>
{{ out }}
<pre>
[strings, sample, sorted, Here, some, are, be, to]
</pre>
=={{header|JavaScript}}==
===ES5===
<
var result = b.length - a.length;
if (result == 0)
Line 2,010 ⟶ 2,252:
var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
test.sort(lengthSorter);
alert( test.join(' ') ); // strings sample sorted Here some are be to</
Or, abstracting a little for simpler composition of compound and derived searches (ASC and DESC, secondary sorts):
<
'use strict';
Line 2,134 ⟶ 2,376:
.sort(on(flip(compare), population))
});
})();</
===ES6===
<
'use strict';
Line 2,212 ⟶ 2,454:
// MAIN ---
return main();
})();</
{{Out}}
<pre>be
Line 2,238 ⟶ 2,480:
As illustrated in the example, the comparator may be any jq filter, whether or not it is defined as a function.
<
if length < 2 then . # it is already sorted
else .[0] as $pivot
Line 2,259 ⟶ 2,501:
end )
| (.[0] | quicksort(cmp) ) + .[1] + (.[2] | quicksort(cmp) )
end ;</
Example:
<
["z", "yz", "ab", "c"]
| quicksort( (.[0]|length) > (.[1]|length) or ( (.[0]|length) == (.[1]|length) and .[0] < .[1] ) )
</syntaxhighlight>
{{Out}}
<
"ab",
"yz",
"c",
"z"
]</
=={{header|Julia}}==
My word list source is the opening sentence of Shelly's [http://www.gutenberg.org/cache/epub/84/pg84.txt Frankenstein].
<
commencement of an enterprise which you have regarded with such evil
forebodings.""", r"\W+"))
Line 2,282 ⟶ 2,524:
sort!(wl; by=x -> (-length(x), lowercase(x)))
println("\nSorted list:\n - ", join(wl, "\n - "))
</syntaxhighlight>
{{out}}
Line 2,339 ⟶ 2,581:
A translation from Java, also showing the seamless interop between Java and Kotlin code.
<
fun main(args: Array<String>) {
Line 2,360 ⟶ 2,602:
printArray("Sorted:", strings)
}</
{{out}}
Line 2,369 ⟶ 2,611:
A more idiomatic version (1.3):
<
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
Line 2,377 ⟶ 2,619:
println("Sorted: $sorted")
}</
Using a custom comparator as requested by task description:
<
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
Line 2,394 ⟶ 2,636:
println("Sorted: $sorted")
}</
Faster when computing length and lowercase only once per value ([[wp:Schwartzian transform|Schwartzian transform]]):
<
val strings = listOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
println("Unsorted: $strings")
Line 2,411 ⟶ 2,653:
println("Sorted: $sorted")
}</
Line 2,417 ⟶ 2,659:
<pre>Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted: [strings, sample, sorted, Here, some, are, be, to]</pre>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def sortbylength
{def sortbylength.i
{lambda {:x :a}
{if {A.empty? :a}
then {A.new :x}
else {if {> {W.length :x} {W.length {A.first :a}}}
then {A.addfirst! :x :a}
else {A.addfirst! {A.first :a}
{sortbylength.i :x {A.rest :a}}} }}}}
{def sortbylength.r
{lambda {:a1 :a2}
{if {A.empty? :a1}
then :a2
else {sortbylength.r {A.rest :a1}
{sortbylength.i {A.first :a1} :a2}} }}}
{lambda {:s}
{S.replace (\[|\]) by in
{S.replace , by space in
{A.disp {sortbylength.r {A.new :s} {A.new}} }}}}}
-> sortbylength
{sortbylength here are Some sample strings to be sorted}
-> strings sample sorted here Some are to be
</syntaxhighlight>
=={{header|Lua}}==
<
function stringSorter(a, b)
Line 2,430 ⟶ 2,703:
-- print sorted table
for k,v in pairs(test) do print(v) end</
{{out}}
Line 2,439 ⟶ 2,712:
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Class Quick {
Line 2,519 ⟶ 2,792:
}
Checkit
</syntaxhighlight>
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.
<syntaxhighlight lang="m2000 interpreter">
Group Quick {
Module ForStringsSpecial {
Line 2,553 ⟶ 2,826:
}
}
</syntaxhighlight>
{{out}}
Line 2,595 ⟶ 2,868:
=={{header|Maple}}==
<
local len1, len2;
len1 := StringTools:-Length(s1);
Line 2,609 ⟶ 2,882:
L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted", "Tooo"];
sort(L, Compare_fn);</
{{out}}
<pre>
Line 2,619 ⟶ 2,892:
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:
<
If[StringLength[x] == StringLength[y],
OrderedQ[{x, y}],
Line 2,625 ⟶ 2,898:
]
words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"};
Sort[words,StringOrderQ]</
gives back:
<pre>{sambaa,sander,second,sifted,sorted,sunday,and,for,on,a}</pre>
=={{header|Maxima}}==
<
s: tokens("Lorem ipsum dolor sit amet consectetur adipiscing elit Sed non risus Suspendisse\
lectus tortor dignissim sit amet adipiscing nec ultricies sed dolor")$
Line 2,637 ⟶ 2,910:
["Suspendisse", "consectetur", "adipiscing", "adipiscing", "dignissim", "ultricies",
"lectus", "tortor", "Lorem", "dolor", "dolor", "ipsum", "risus", "amet", "amet",
"elit", "Sed", "nec", "non", "sed", "sit", "sit"]</
=={{header|MAXScript}}==
<
(
case of
Line 2,662 ⟶ 2,935:
strList = #("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
qSort strList myCmp
print strList</
=={{header|min}}==
{{works with|min|0.19.3}}
<
(((length) (length)) spread <) sort print</
{{out}}
<pre>
Line 2,674 ⟶ 2,947:
=={{header|Nemerle}}==
<
module CustomSort
Line 2,686 ⟶ 2,959:
WriteLine(strings2.Sort((x, y) => x.CompareTo(y)))
}
}</
{{out}}
<pre>[different, strings, length, these, are, of]
Line 2,693 ⟶ 2,966:
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 2,725 ⟶ 2,998:
else signal IllegalArgumentException('Arguments must be Strings')
return cRes
</syntaxhighlight>
{{out}}
<pre>
Line 2,733 ⟶ 3,006:
=={{header|Nial}}==
<
=+-------+------+------+----+----+---+--+--+
=|strings|sample|sorted|Here|some|are|be|to|
=+-------+------+------+----+----+---+--+--+</
=={{header|Nim}}==
<
var strings = "here are Some sample strings to be sorted".split(' ')
Line 2,749 ⟶ 3,022:
)
echo strings</
{{out}}
Line 2,755 ⟶ 3,028:
=={{header|Objeck}}==
<
class Test {
Line 2,811 ⟶ 3,084:
return @s;
}
}</
<pre>
Line 2,821 ⟶ 3,094:
{{works with|Cocoa|Mac OS X 10.6+}}
Using blocks:
<
#define esign(X) (((X)>0)?1:(((X)<0)?-1:0))
Line 2,848 ⟶ 3,121:
}
return EXIT_SUCCESS;
}</
Line 2,854 ⟶ 3,127:
{{works with|Cocoa}}
<
@interface NSString (CustomComp)
Line 2,889 ⟶ 3,162:
}
return EXIT_SUCCESS;
}</
This example can also be written using sort descriptors:
{{works with|GNUstep}}
{{works with|Cocoa}}
<
int main()
Line 2,911 ⟶ 3,184:
return 0;
}</
=={{header|OCaml}}==
<
if String.length s1 <> String.length s2 then
compare (String.length s2) (String.length s1)
else
String.compare (String.lowercase s1) (String.lowercase s2)</
List:
<
val strings : string list =
["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"]
# List.sort mycmp strings;;
- : string list =
["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"]</
Array:
<
val strings : string array =
[|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|]
Line 2,936 ⟶ 3,209:
# strings;;
- : string array =
[|"strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"|]</
=={{header|Oforth}}==
<
s size self size > ifTrue: [ true return ]
s size self size < ifTrue: [ false return ]
Line 2,946 ⟶ 3,219:
["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]
sortWith(#customCmp) println</
{{out}}
Line 2,954 ⟶ 3,227:
=={{header|Ol}}==
<
(import (scheme char))
Line 2,971 ⟶ 3,244:
"hendrerit" "viverra" "turpis" "ac" "sagittis"
"arcu" "pharetra" "id")))
</syntaxhighlight>
=={{header|ooRexx}}==
<
say 'Sorted in order of descending length, and in ascending lexicographic order'
say A~sortWith(.DescLengthAscLexical~new)~makeString
Line 2,983 ⟶ 3,256:
if left~length==right~length
then return left~caselessCompareTo(right)
else return right~length-left~length</
{{out}}
<pre>
Line 2,998 ⟶ 3,271:
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
uses generics 'containing sort macros
uses console
Line 3,033 ⟶ 3,306:
next
pause
</syntaxhighlight>
=={{header|Oz}}==
<
fun {LexicographicLessThan Xs Ys}
for
Line 3,056 ⟶ 3,329:
Strings = ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]
in
{ForAll {Sort Strings LessThan} System.showInfo}</
=={{header|PARI/GP}}==
<
vecsort(v,cmp)</
=={{header|Pascal}}==
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
program CustomComparator;
{$mode objfpc}{$h+}
uses
Classes, SysUtils, Math;
function Compare(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := CompareValue(Length(List[Index2]), Length(List[Index1]));
if Result = 0 then
Result := CompareText(List[Index1], List[Index2]);
end;
const
Sample = 'Here are some sample strings to be sorted';
begin
with TStringList.Create do
try
AddStrings(Sample.Split([' '], TStringSplitOptions.ExcludeEmpty));
CustomSort(@Compare);
WriteLn(string.Join(', ', ToStringArray));
finally
Free;
end;
Readln;
end.
</syntaxhighlight>
{{out}}
<pre>
strings, sample, sorted, Here, some, are, be, to
</pre>
=={{header|Perl}}==
<
@strings = qw/Here are some sample strings to be sorted/;
Line 3,082 ⟶ 3,386:
sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] }
map { [ $_, length, lc ] }
@strings;</
{{out}}
<pre>strings sample sorted Here some are be to
Line 3,090 ⟶ 3,394:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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>
Line 3,099 ⟶ 3,403:
<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>
<!--</
{{out}}
<pre>
Line 3,107 ⟶ 3,411:
=={{header|PHP}}==
{{works with|PHP|4.4.4 CLI}}
<
function mycmp($s1, $s2)
{
Line 3,117 ⟶ 3,421:
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?></
=={{header|PicoLisp}}==
Line 3,123 ⟶ 3,427:
PicoLisp returns an ascending list (of any type). To get a result in descending
order, the "greater than" function can be supplied
<
-> ("ghi" "def" "abc")</
or simply the result reversed (which is, btw, the most efficient way)
<
-> ("ghi" "def" "abc")</
=={{header|PL/I}}==
Line 3,133 ⟶ 3,437:
'''Platform:''' [[WIN]]
<
DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */
Line 3,202 ⟶ 3,506:
put skip;
END RMERGE;</
=={{header|Pop11}}==
<
define compare(s1, s2);
lvars k = length(s2) - length(s1);
Line 3,225 ⟶ 3,529:
l2 = length(s2);
l1 > l2 or (l1 == l2 and alphabefore(uppertolower(s1), uppertolower(s2)))
enddefine;</
=={{header|PowerBASIC}}==
Line 3,231 ⟶ 3,535:
{{works with|PB/CC|4}}
<
'if p1 should be first, returns -1
'if p2 should be first, returns 1
Line 3,256 ⟶ 3,560:
'pb's built-in sorting; "USING" tells it to use our custom comparator
ARRAY SORT x(), USING Sorter()
END FUNCTION</
=={{header|PowerShell}}==
The <code>Sort-Object</code> cmdlet accepts script blocks as arguments as well as multiple criteria after which to sort.
<
$list | Sort-Object {-$_.Length},{$_}</
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}}==
Works with SWI-Prolog (Tested on Version 8.1.19). Duplicates (if any) are removed.
<
L = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted" ],
predsort(my_comp, L, L1),
Line 3,284 ⟶ 3,588:
my_write(W) :-
format('~s ', [W]).
</syntaxhighlight>
{{out}}
Line 3,298 ⟶ 3,602:
=={{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.
<
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)</
{{out}}
<
===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.
<
return cmp(len(s2), len(s1)) or cmp(s1.upper(), s2.upper())
print sorted(strings, cmp=mycmp)</
=={{header|Quackery}}==
<
witheach
[ upper join ] ] is upper$ ( $ --> )
Line 3,334 ⟶ 3,638:
$ "sharna pax and hed on a poal when the ardship of Cambry come out of his hoal"
nest$ sortwith comparator
witheach [ echo$ sp ]</
{{out}}
Line 3,344 ⟶ 3,648:
=={{header|R}}==
<
print(v[order(-nchar(v), tolower(v))])</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 3,365 ⟶ 3,669:
(sort2 '("Some" "pile" "of" "words"))
;; -> '("words" "pile" "Some" "of")
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)<br>
Primary sort by length of string, then break ties by sorting alphabetically (ignoring case).
<syntaxhighlight lang="raku"
put @strings.sort:{.chars, .lc};
put sort -> $x { $x.chars, $x.lc }, @strings;</
{{out}}
<pre>be to are Here some sample sorted strings
Line 3,379 ⟶ 3,683:
=={{header|REXX}}==
<
/* using mycmp function for the sort order */
/**********************************************************************
Line 3,508 ⟶ 3,812:
Otherwise res=0
End
RETURN res</
{{out}}
<pre>
Line 3,534 ⟶ 3,838:
=={{header|Ring}}==
<
load "stdlib.ring"
Line 3,569 ⟶ 3,873:
see oList[n] [1] + nl
next
</syntaxhighlight>
Output:
<pre>
Line 3,585 ⟶ 3,889:
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.
<
p words.sort_by {|word| [-word.size, word.downcase]}</
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.
<
d != 0 ? d : a.upcase <=> b.upcase}</
=={{header|Rust}}==
<
fn main() {
let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"];
Line 3,599 ⟶ 3,903:
println!("{:?}", words);
}
</syntaxhighlight>
=={{header|Sather}}==
<
custom_comp(a, b:STR):BOOL is
Line 3,616 ⟶ 3,920:
loop #OUT + s.elt! + "\n"; end;
end;
end;</
=={{header|Scala}}==
<
val cmp=a.size-b.size
(if (cmp==0) -a.compareTo(b) else cmp) > 0
}</
{{out}}
<pre>List(strings, sample, sorted, Here, some, are, be, to)</pre>
=={{header|Scheme}}==
<
;;a sort function may be predefined, or available through srfi 95
(define (mypred? a b)
Line 3,636 ⟶ 3,940:
(> len-a len-b))))
(sort '("sorted" "here" "strings" "sample" "Some" "are" "be" "to") mypred?) </
{{out}}
<
Line 3,644 ⟶ 3,948:
{{works with|Gauche Scheme}}
<
"This" "Is" "A" "Set" "Of" "Strings" "To" "Sort" "duplicated"
"this" "is" "a" "set" "of" "strings" "to" "sort" "duplicated"))
Line 3,655 ⟶ 3,959:
(apply string-ci<? two)
(apply > sizes)))))
</syntaxhighlight>
{{out}}
<pre>
Line 3,663 ⟶ 3,967:
=={{header|Sidef}}==
<
var strings = %w(Here are some sample strings to be sorted);
var sorted = strings.sort(mycmp);</
=={{header|Slate}}==
<
words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]</
=={{header|Smalltalk}}==
<
sortBlock:
[:first :second | (second size = first size)
ifFalse: [second size < first size]
ifTrue: [first < second]]</
the above creates a sorted collection;
an inplace sort of arrayed collections is done with eg.:
<
sort:[:a :b | a reversed < b reversed]</
=={{header|Standard ML}}==
List:
{{works with|SML/NJ}}
<
if size s1 <> size s2 then
size s2 > size s1
else
String.map Char.toLower s1 > String.map Char.toLower s2</
<
val strings = ["Here","are","some","sample","strings","to","be","sorted"]
: string list
- ListMergeSort.sort mygt strings;
val it = ["strings","sample","sorted","Here","some","are","be","to"]
: string list</
Array:
{{works with|SML/NJ}}
<
if size s1 <> size s2 then
Int.compare (size s2, size s1)
else
String.compare (String.map Char.toLower s1, String.map Char.toLower s2)</
<
val strings = [|"Here","are","some","sample","strings","to","be","sorted"|]
: string array
Line 3,713 ⟶ 4,017:
- strings;
val it = [|"strings","sample","sorted","Here","some","are","be","to"|]
: string array</
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
var list = ["this",
Line 3,746 ⟶ 4,050:
return lhsCount > rhsCount
}</
{{works with|Swift|1.2}}
<
var list = ["this",
Line 3,777 ⟶ 4,081:
return lhsCount > rhsCount
}</
=={{header|Tcl}}==
<
set la [string length $a]
set lb [string length $b]
Line 3,792 ⟶ 4,096:
set strings {here are Some sample strings to be sorted}
lsort -command sorter $strings ;# ==> strings sample sorted here Some are be to</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort"
Line 3,809 ⟶ 4,113:
PRINT "2. setofstrings sorted"
*{sorted}
</syntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 3,852 ⟶ 4,156:
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.
<
#show+
data = <'this','is','a','list','of','strings','to','be','sorted'>
example = psort<not leql,lleq+ ~* ~&K31K30piK26 letters> data</
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 3,873 ⟶ 4,177:
=={{header|Visual Basic .NET}}==
<
Module Sorting_Using_a_Custom_Comparator
Line 3,890 ⟶ 4,194:
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module</
=={{header|Wren}}==
{{libheader|Wren-sort}}
<
var cmp = Fn.new { |s, t|
Line 3,905 ⟶ 4,209:
System.print("Unsorted: %(strings)")
Sort.insertion(strings, cmp)
System.print("Sorted : %(strings)")</
{{out}}
Line 3,911 ⟶ 4,215:
Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted : [strings, sample, sorted, Here, some, are, be, to]
</pre>
=={{header|Zig}}==
'''Works with:''' 0.11.x, 0.12.0-dev.1390+94cee4fb2
For 0.10.x, replace std.mem.sort with std.sort.sort .
<syntaxhighlight lang="zig">const std = @import("std");
/// Sort by descending length and ascending lexicographical order.
/// If true, element will remain on it's place.
fn lessThanFn(context: void, left: []const u8, right: []const u8) bool {
_ = context;
// Sort by descending length
switch (std.math.order(left.len, right.len)) {
.lt => return false,
.eq => {},
.gt => return true,
}
// If length is equal, sort by ascending lexicographical order
return switch (std.ascii.orderIgnoreCase(left, right)) {
.lt => true,
.eq => false,
.gt => false,
};
}
pub fn main() void {
var words = [_][]const u8{ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
std.debug.print("Before: [ ", .{});
for (words) |word| {
std.debug.print("\"{s}\" ", .{word});
}
std.debug.print("]\n", .{});
std.mem.sort([]const u8, &words, {}, lessThanFn);
std.debug.print("After: [ ", .{});
for (words) |word| {
std.debug.print("\"{s}\" ", .{word});
}
std.debug.print("]\n", .{});
}</syntaxhighlight>
{{out}}
<pre>
Before: [ "Here" "are" "some" "sample" "strings" "to" "be" "sorted" ]
After: [ "strings" "sample" "sorted" "Here" "some" "are" "be" "to" ]
</pre>
=={{header|zkl}}==
<
r:=s.sort(fcn(a,b){
an,bn := a.len(),b.len();
if(an==bn)(a.toLower() < b.toLower()) else (an > bn)
});
r.pump(Console.println);</
{{out}}
<pre>
|