Sort numbers lexicographically: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Minor tidy)
 
(12 intermediate revisions by 8 users not shown)
Line 18: Line 18:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V n = 13
<syntaxhighlight lang="11l">V n = 13
print(sorted(Array(1..n), key' i -> String(i)))</lang>
print(sorted(Array(1..n), key' i -> String(i)))</syntaxhighlight>


{{out}}
{{out}}
Line 27: Line 27:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC PrintArray(INT ARRAY a INT size)
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
INT i


Line 86: Line 86:
Test(a,COUNT_A)
Test(a,COUNT_A)
Test(b,COUNT_B)
Test(b,COUNT_B)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_numbers_lexicographically.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_numbers_lexicographically.png Screenshot from Atari 8-bit computer]
Line 102: Line 102:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>WITH Ada.Containers.Generic_Array_Sort, Ada.Text_IO;
<syntaxhighlight lang="ada">WITH Ada.Containers.Generic_Array_Sort, Ada.Text_IO;
USE Ada.Text_IO;
USE Ada.Text_IO;
PROCEDURE Main IS
PROCEDURE Main IS
Line 121: Line 121:
Show (21);
Show (21);
END Main;
END Main;
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 129: Line 129:
</pre>
</pre>
{{out}}
{{out}}

=={{header|ALGOL 68}}==
Uses code from the [[Sorting algorithms/Insertion sort]] tasl - included here for convenience.<br>
<syntaxhighlight lang="algol68">
BEGIN # sort numbers lexicographically #

# code from the Sorting algorithms/Insertion sort task #
MODE DATA = STRING;

PROC in place insertion sort = (REF[]DATA item)VOID:
BEGIN
INT first := LWB item;
INT last := UPB item;
INT j;
DATA value;
FOR i FROM first + 1 TO last DO
value := item[i];
j := i - 1;
WHILE ( j >= LWB item AND j <= UPB item | item[j]>value | FALSE ) DO
item[j + 1] := item[j];
j -:= 1
OD;
item[j + 1] := value
OD
END # in place insertion sort #;

# end code from the Sorting algorithms/Insertion sort task #

# returns s converted to an integer, NB: no error checking #
OP TOINT = ( STRING s )INT:
BEGIN
INT result := 0;
FOR i FROM LWB s TO UPB s DO
result *:= 10 +:= ( ABS s[ i ] - ABS "0" )
OD;
result
END # TOINT # ;

# returns a array of integers 1..n sorted lexicographically #
PROC lexicographic order = ( INT n )[]INT:
BEGIN
[ 1 : n ]STRING v; FOR i TO n DO v[ i ] := whole( i, 0 ) OD;
in place insertion sort( v );
[ 1 : n ]INT result;
FOR i TO n DO result[ i ] := TOINT v[ i ] OD;
result
END # lexicographic order # ;

# prints the elements of a #
PROC show int array = ( []INT a )VOID:
BEGIN
print( ( "[" ) );
FOR i FROM LWB a TO UPB a DO print( ( " ", whole( a[ i ], 0 ) ) ) OD;
print( ( " ]", newline ) )
END # show int array # ;

# test cases #
show int array( lexicographic order( 13 ) );
show int array( lexicographic order( 21 ) )

END
</syntaxhighlight>
{{out}}
<pre>
[ 1 10 11 12 13 2 3 4 5 6 7 8 9 ]
[ 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9 ]
</pre>


=={{header|APL}}==
=={{header|APL}}==
Line 143: Line 210:
For fast execution of the task as specified, this take on the [https://www.rosettacode.org/wiki/Sort_numbers_lexicographically#BBC_BASIC BBC BASIC] method below generates the integers in the required order:
For fast execution of the task as specified, this take on the [https://www.rosettacode.org/wiki/Sort_numbers_lexicographically#BBC_BASIC BBC BASIC] method below generates the integers in the required order:


<lang applescript>on oneToNLexicographically(n)
<syntaxhighlight lang="applescript">on oneToNLexicographically(n)
script o
script o
property output : {}
property output : {}
Line 167: Line 234:


oneToNLexicographically(123)
oneToNLexicographically(123)
--> {1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121, 122, 123, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}</lang>
--> {1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121, 122, 123, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}</syntaxhighlight>


In the unlikely event of it ever being necessary to sort a ''given'' list of integers in this fashion, one possibility is to create another list containing text versions of the integers and to sort this while rearranging the integer versions in parallel.
In the unlikely event of it ever being necessary to sort a ''given'' list of integers in this fashion, one possibility is to create another list containing text versions of the integers and to sort this while rearranging the integer versions in parallel.


<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later.
<lang applescript>use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>
use sorter : script ¬
"Custom Iterative Ternary Merge Sort" -- <www.macscripter.net/t/timsort-and-nigsort/71383/3>


on join(lst, delim)
on sortLexicographically(integerList) -- Sorts integerList in place.
set astid to AppleScript's text item delimiters
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set AppleScript's text item delimiters to delim
set textList to paragraphs of (integerList as text)
set txt to lst as text
set AppleScript's text item delimiters to astid
set AppleScript's text item delimiters to astid
return txt
end join

on sortLexicographically(integerList)
set textList to paragraphs of join(integerList, linefeed)
-- Sort textList, echoing the moves in integerList.
considering hyphens but ignoring numeric strings
considering hyphens but ignoring numeric strings
tell sorter to sort(textList, 1, -1, {slave:{integerList}})
tell sorter to sort(textList, 1, -1, {slave:{integerList}})
Line 185: Line 259:


-- Test code:
-- Test code:
local someIntegers
set someIntegers to {1, 2, -6, 3, 4, 5, -10, 6, 7, 8, 9, 10, 11, 12, 13, -2, -5, -1, -4, -3, 0}
set someIntegers to {1, 2, -6, 3, 4, 5, -10, 6, 7, 8, 9, 10, 11, 12, 13, -2, -5, -1, -4, -3, 0}
sortLexicographically(someIntegers)
sortLexicographically(someIntegers)
return someIntegers
return someIntegers</syntaxhighlight>

--> {-1, -10, -2, -3, -4, -5, -6, 0, 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}</lang>
{{output}}
<syntaxhighlight lang="applescript">{-1, -10, -2, -3, -4, -5, -6, 0, 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>arr: 1..13
<syntaxhighlight lang="rebol">arr: 1..13
print sort map arr => [to :string &]</lang>
print sort map arr => [to :string &]</syntaxhighlight>


{{out}}
{{out}}


<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>

=={{header|ATS}}==

The program converts the integers to strings, sorts the strings, then converts the strings back to integers.
The method can be used to sort any sequence of non-negative integers.

(Radix sorting the numbers in their original form is another possible approach.)

<syntaxhighlight lang="ats">
(* The Rosetta Code lexicographic sort task. *)

#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"

#define NIL list_nil ()
#define :: list_cons

fn
uint_to_digit (n : uint)
: char =
int2char0 (g0u2i n + char2int0 '0')

fn
int_to_string {n : nat}
(n : int n)
: string =
if iseqz n then
"0"
else
let
fun
loop {i : nat | i <= 20}
.<i>.
(buf : &array (char, 21),
i : int i,
n : uint)
: [j : nat | j <= 20]
int j =
if (i = 0) + (iseqz n) then
i
else
let
val i1 = pred i
in
buf[i1] := uint_to_digit (n mod 10u);
loop (buf, i1, n / 10u)
end

var buf = @[char][21] ('\0')
val j = loop (buf, 20, g0i2u n)
val p = ptr_add<char> (addr@ buf, j)
in
strptr2string (string0_copy ($UN.cast{string} p))
end

fn
iota1 {n : pos}
(n : int n)
: list ([i : pos | i <= n] int i, n) =
let
typedef t = [i : pos | i <= n] int i

fun
loop {i : nat | i <= n}
.<i>.
(i : int i,
accum : list (t, n - i))
: list (t, n) =
if i = 0 then
accum
else
loop (pred i, i :: accum)
in
loop (n, NIL)
end

fn
reverse_map_numbers_to_strings
{n : int}
(nums : list ([i : nat] int i, n))
: list (string, n) =
let
typedef t = [i : nat] int i

fun
loop {i : nat | i <= n}
.<n - i>.
(nums : list (t, n - i),
accum : list (string, i))
: list (string, n) =
case+ nums of
| NIL => accum
| head :: tail =>
loop {i + 1} (tail, int_to_string head :: accum)

prval () = lemma_list_param nums
in
loop {0} (nums, NIL)
end

fn
reverse_map_strings_to_numbers
{n : int}
(strings : list (string, n))
: list (int, n) =
let
macdef string_to_int (s) =
$extfcall (int, "atoi", ,(s))

fun
loop {i : nat | i <= n}
.<n - i>.
(strings : list (string, n - i),
accum : list (int, i))
: list (int, n) =
case+ strings of
| NIL => accum
| head :: tail =>
loop {i + 1} (tail, string_to_int head :: accum)

prval () = lemma_list_param strings
in
loop {0} (strings, NIL)
end
fn
lexicographic_iota1
{n : pos}
(n : int n)
: list (int, n) =
let
val numstrings =
reverse_map_numbers_to_strings (iota1 n)

(* One could use a MSB-first radix sort here, but I will use what
is readily available. *)
implement
list_mergesort$cmp<string> (x, y) =
~compare (x, y)
in
reverse_map_strings_to_numbers
(list_vt2t (list_mergesort<string> numstrings))
end

implement
main0 () =
begin
println! (lexicographic_iota1 13);
println! (lexicographic_iota1 100)
end
</syntaxhighlight>

{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW lexicographic_sort.dats -lgc && ./a.out
1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
1, 10, 100, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>n2lexicog(n){
<syntaxhighlight lang="autohotkey">n2lexicog(n){
Arr := [], list := ""
Arr := [], list := ""
loop % n
loop % n
Line 208: Line 441:
Arr.Push(v)
Arr.Push(v)
return Arr
return Arr
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>n := 13
Examples:<syntaxhighlight lang="autohotkey">n := 13
x := n2lexicog(n)
x := n2lexicog(n)
for k, v in x
for k, v in x
output .= v ", "
output .= v ", "
MsgBox % "[" Trim(output, ", ") "]" ; show output
MsgBox % "[" Trim(output, ", ") "]" ; show output
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
Line 220: Line 453:
=={{header|AWK}}==
=={{header|AWK}}==
===Robust with checks===
===Robust with checks===
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SORT_NUMBERS_LEXICOGRAPHICALLY.AWK
# syntax: GAWK -f SORT_NUMBERS_LEXICOGRAPHICALLY.AWK
#
#
Line 265: Line 498:
return(str)
return(str)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 279: Line 512:
===Alternative, using GAWK's builtin sort===
===Alternative, using GAWK's builtin sort===
This version explicitly casts integers as strings during list generation and uses the builtin sort available in GAWK on element values.
This version explicitly casts integers as strings during list generation and uses the builtin sort available in GAWK on element values.
<lang AWK>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
n=13
n=13
for (i=1; i<=n; i++)
for (i=1; i<=n; i++)
Line 286: Line 519:
for (k in a)
for (k in a)
printf "%d ", a[k]
printf "%d ", a[k]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 293: Line 526:
=={{header|BaCon}}==
=={{header|BaCon}}==
Create a delimited string with numbers and use SORT$.
Create a delimited string with numbers and use SORT$.
<lang bacon>CONST n = 13
<syntaxhighlight lang="bacon">CONST n = 13
FOR x = 1 TO n
FOR x = 1 TO n
result$ = APPEND$(result$, 0, STR$(x))
result$ = APPEND$(result$, 0, STR$(x))
NEXT
NEXT
PRINT SORT$(result$)</lang>
PRINT SORT$(result$)</syntaxhighlight>
{{out}}
{{out}}
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
Line 303: Line 536:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> N%=13
<syntaxhighlight lang="bbcbasic"> N%=13
PRINT "[" LEFT$(FNLexOrder(0)) "]"
PRINT "[" LEFT$(FNLexOrder(0)) "]"
END
END
Line 312: Line 545:
IF i% > 0 s$+=STR$i% + "," + FNLexOrder(i% * 10)
IF i% > 0 s$+=STR$i% + "," + FNLexOrder(i% * 10)
NEXT
NEXT
=s$</lang>
=s$</syntaxhighlight>
{{out}}
{{out}}
<pre>[1,10,11,12,13,2,3,4,5,6,7,8,9]</pre>
<pre>[1,10,11,12,13,2,3,4,5,6,7,8,9]</pre>

=={{header|BQN}}==
<syntaxhighlight lang="bqn">Task ← ⍋∘(•Fmt¨)⊸⊏1+↕

Task 13</syntaxhighlight>
{{out}}
<pre>⟨ 1 10 11 12 13 2 3 4 5 6 7 8 9 ⟩</pre>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <math.h>
<syntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 367: Line 607:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>

{{out}}
{{out}}
<pre>
<pre>
Line 382: Line 621:
=={{header|C sharp}}==
=={{header|C sharp}}==
{{works with|C sharp|7}}
{{works with|C sharp|7}}
<lang csharp>using static System.Console;
<syntaxhighlight lang="csharp">using static System.Console;
using static System.Linq.Enumerable;
using static System.Linq.Enumerable;


Line 392: Line 631:


public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 403: Line 642:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>
#include <numeric>
#include <numeric>
Line 443: Line 682:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 455: Line 694:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(def n 13)
<syntaxhighlight lang="clojure">(def n 13)
(sort-by str (range 1 (inc n)))</lang>
(sort-by str (range 1 (inc n)))</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 10 11 12 13 2 3 4 5 6 7 8 9)</pre>
<pre>(1 10 11 12 13 2 3 4 5 6 7 8 9)</pre>
Line 462: Line 701:
=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
{{works with|GnuCOBOL}}
<lang cobol> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. LexicographicalNumbers.
program-id. LexicographicalNumbers.


Line 497: Line 736:
display "]"
display "]"
stop run
stop run
.</lang>
.</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]</pre>
<pre>[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]</pre>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(defun lexicographic-sort (n)
(defun lexicographic-sort (n)
(sort (alexandria:iota n :start 1) #'string<= :key #'write-to-string))
(sort (alexandria:iota n :start 1) #'string<= :key #'write-to-string))
(lexicographic-sort 13)
(lexicographic-sort 13)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 512: Line 751:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting kernel math.parser math.ranges sequences
<syntaxhighlight lang="factor">USING: formatting kernel math.parser math.ranges sequences
sorting ;
sorting ;
IN: rosetta-code.lexicographical-numbers
IN: rosetta-code.lexicographical-numbers
Line 520: Line 759:
[ string>number ] map ;
[ string>number ] map ;
{ 13 21 -22 } [ dup lex-order "%3d: %[%d, %]\n" printf ] each</lang>
{ 13 21 -22 } [ dup lex-order "%3d: %[%d, %]\n" printf ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 530: Line 769:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_numbers_lexicographically}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.


'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.


[[File:Fōrmulæ - Sort numbers lexicographically 01.png]]
In '''[https://formulae.org/?example=Sort_numbers_lexicographically this]''' page you can see the program(s) related to this task and their results.

'''Test case'''

[[File:Fōrmulæ - Sort numbers lexicographically 02.png]]

[[File:Fōrmulæ - Sort numbers lexicographically 03.png]]


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>function leq( n as integer, m as integer ) as boolean
<syntaxhighlight lang="freebasic">function leq( n as integer, m as integer ) as boolean
if str(n)<=str(m) then return true else return false
if str(n)<=str(m) then return true else return false
end function
end function
Line 577: Line 822:
if i<n-1 then print ", ";
if i<n-1 then print ", ";
next i
next i
print "]"</lang>
print "]"</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
? 13
? 13
Line 584: Line 829:


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


import (
import (
Line 614: Line 859:
fmt.Printf("%3d: %v\n", n, lexOrder(n))
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 628: Line 873:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>import Data.List (sort)
<syntaxhighlight lang="haskell">import Data.List (sort)


task :: (Ord b, Show b) => [b] -> [b]
task :: (Ord b, Show b) => [b] -> [b]
task = map snd . sort . map (\i -> (show i, i))
task = map snd . sort . map (\i -> (show i, i))


main = print $ task [1 .. 13]</lang>
main = print $ task [1 .. 13]</syntaxhighlight>


Which we could also write, in a point-free style as:
Which we could also write, in a point-free style as:
<lang haskell>import Data.List (sort)
<syntaxhighlight lang="haskell">import Data.List (sort)


task
task
Line 643: Line 888:
task = map snd . sort . map (show >>= (,))
task = map snd . sort . map (show >>= (,))


main = print $ task [1 .. 13]</lang>
main = print $ task [1 .. 13]</syntaxhighlight>


and the simplest approach might be ''sortOn show'' (which only evaluates ''show'' once for each item).
and the simplest approach might be ''sortOn show'' (which only evaluates ''show'' once for each item).


<lang haskell>import Data.List (sortOn)
<syntaxhighlight lang="haskell">import Data.List (sortOn)


main :: IO ()
main :: IO ()
main = print $ sortOn show [1 .. 13]</lang>
main = print $ sortOn show [1 .. 13]</syntaxhighlight>


{{out}}
{{out}}
Line 658: Line 903:
{{works with|Isabelle|2020}}
{{works with|Isabelle|2020}}


<lang Isabelle>theory LexList
<syntaxhighlight lang="isabelle">theory LexList
imports
imports
Main
Main
Line 680: Line 925:


value ‹sort (map ascii_of (upt 1 13))›
value ‹sort (map ascii_of (upt 1 13))›
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 688: Line 933:
=={{header|J}}==
=={{header|J}}==


<lang J>task=: [: (/: ":"0) 1 + i.
<syntaxhighlight lang="j">task=: [: (/: ":"0) 1 + i.
task 13</lang>
task 13</syntaxhighlight>


{{out}}
{{out}}
Line 698: Line 943:
<br>
<br>
Requires Java 8 or later.
Requires Java 8 or later.
<lang java>import java.util.List;
<syntaxhighlight lang="java">import java.util.List;
import java.util.stream.*;
import java.util.stream.*;


Line 723: Line 968:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 735: Line 980:
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]
</pre>
</pre>

=={{header|K}}==
<syntaxhighlight lang="k">task: 1+<$1+!:

task 13</syntaxhighlight>
{{out}}
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 773: Line 1,025:
_fillarray arr ${N}
_fillarray arr ${N}


print -- ${arr[*]}</lang>
print -- ${arr[*]}</syntaxhighlight>
{{out}}<pre>
{{out}}
1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Works with gojq, the Go implementation of jq'''
<lang jq>def sort_range($a;$b): [range($a;$b)] | sort_by(tostring);
<syntaxhighlight lang="jq">def sort_range($a;$b): [range($a;$b)] | sort_by(tostring);


# Example
# Example
# jq's index origin is 0, so ...
# jq's index origin is 0, so ...
sort_range(1;14)</lang>
sort_range(1;14)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 791: Line 1,043:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>lexorderedsequence(n) = sort(collect(n > 0 ? (1:n) : n:1), lt=(a,b) -> string(a) < string(b))
<syntaxhighlight lang="julia">lexorderedsequence(n) = sort(collect(n > 0 ? (1:n) : n:1), lt=(a,b) -> string(a) < string(b))


for i in [0, 5, 13, 21, -32]
for i in [0, 5, 13, 21, -32]
println(lexorderedsequence(i))
println(lexorderedsequence(i))
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
[0, 1]
[0, 1]
Line 806: Line 1,058:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// Version 1.2.51
<syntaxhighlight lang="scala">// Version 1.2.51


fun lexOrder(n: Int): List<Int> {
fun lexOrder(n: Int): List<Int> {
Line 823: Line 1,075:
println("${"%3d".format(n)}: ${lexOrder(n)}")
println("${"%3d".format(n)}: ${lexOrder(n)}")
}
}
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 837: Line 1,089:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
1) lexicographically sorting a sequence of numbers
1) lexicographically sorting a sequence of numbers
{S.sort before 1 2 3 4 5 6 7 8 9 10 11 12 13}
{S.sort before 1 2 3 4 5 6 7 8 9 10 11 12 13}
Line 845: Line 1,097:
{A.sort! before {A.new 1 2 3 4 5 6 7 8 9 10 11 12 13}}
{A.sort! before {A.new 1 2 3 4 5 6 7 8 9 10 11 12 13}}
-> [1,10,11,12,13,2,3,4,5,6,7,8,9]
-> [1,10,11,12,13,2,3,4,5,6,7,8,9]
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
Lua's in-built table.sort function will sort a table of strings into lexicographical order by default. This task therefore becomes trivial by converting each number to a string before adding it to the table.
Lua's in-built table.sort function will sort a table of strings into lexicographical order by default. This task therefore becomes trivial by converting each number to a string before adding it to the table.
<lang lua>function lexNums (limit)
<syntaxhighlight lang="lua">function lexNums (limit)
local numbers = {}
local numbers = {}
for i = 1, limit do
for i = 1, limit do
Line 859: Line 1,111:


local numList = lexNums(13)
local numList = lexNums(13)
print(table.concat(numList, " "))</lang>
print(table.concat(numList, " "))</syntaxhighlight>
{{out}}
{{out}}
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Function lexicographical(N) {
Function lexicographical(N) {
Line 917: Line 1,169:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>SortBy[Range[13],ToString]</lang>
<syntaxhighlight lang="mathematica">SortBy[Range[13],ToString]</syntaxhighlight>
{{out}}
{{out}}
<pre>{1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}</pre>
<pre>{1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}</pre>
Line 926: Line 1,178:
=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
In Small Basic there is no string comparison: “a”>”b” the result is “False”, “b”>”a” the result is also “False”. It doesn’t help at all.
In Small Basic there is no string comparison: “a”>”b” the result is “False”, “b”>”a” the result is also “False”. It doesn’t help at all.
<lang smallbasic>' Lexicographical numbers - 25/07/2018
<syntaxhighlight lang="smallbasic">' Lexicographical numbers - 25/07/2018
xx="000000000000000"
xx="000000000000000"
For n=1 To 3
For n=1 To 3
Line 959: Line 1,211:
EndFor
EndFor
TextWindow.WriteLine(nn+":"+Text.GetSubTextToEnd(x,2))
TextWindow.WriteLine(nn+":"+Text.GetSubTextToEnd(x,2))
EndFor </lang>
EndFor </syntaxhighlight>
{{out}}
{{out}}
5:1,2,3,4,5
5:1,2,3,4,5
13:1,10,11,12,13,2,3,4,5,6,7,8,9
13:1,10,11,12,13,2,3,4,5,6,7,8,9
21:1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9
21:1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9

=={{header|MiniScript}}==
Output from REPL.
{{out}}
<pre>
> n = 13
> rng = range(1, 13)
> rng.join(" ").split(" ").sort
["1", "10", "11", "12", "13", "2", "3", "4", "5", "6", "7", "8", "9"]
</pre>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
Line 975: Line 1,237:
- The condensed version shows that there are no reserved keywords
- The condensed version shows that there are no reserved keywords


<syntaxhighlight lang="mumps">
<lang MUMPS>
SortLexographically(n)
SortLexographically(n)
new array,i,j
new array,i,j
Line 981: Line 1,243:
for set j=$order(array(j)) quit:j="" write j
for set j=$order(array(j)) quit:j="" write j
quit
quit
</syntaxhighlight>
</lang>


This could also be written:
This could also be written:


<syntaxhighlight lang="mumps">
<lang MUMPS>
SortLexographically(n) n a,i,j f i=1:1:n s a(i_" ")=""
SortLexographically(n) n a,i,j f i=1:1:n s a(i_" ")=""
f s j=$o(a(j)) q:j="" w j
f s j=$o(a(j)) q:j="" w j
q
q
</syntaxhighlight>
</lang>


;Usage
;Usage


<lang MUMPS> do SortLexographically(13)</lang>
<syntaxhighlight lang="mumps"> do SortLexographically(13)</syntaxhighlight>


{{out}}
{{out}}
Line 1,001: Line 1,263:


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


for n in [0, 5, 13, 21, -22]:
for n in [0, 5, 13, 21, -22]:
let s = if n > 1: toSeq(1..n) else: toSeq(countdown(1, n))
let s = if n > 1: toSeq(1..n) else: toSeq(countdown(1, n))
echo s.sortedByIt($it)</lang>
echo s.sortedByIt($it)</syntaxhighlight>


{{out}}
{{out}}
Line 1,015: Line 1,277:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>printf("%4d: [%s]\n", $_, join ',', sort $_ > 0 ? 1..$_ : $_..1) for 13, 21, -22</lang>
<syntaxhighlight lang="perl">printf("%4d: [%s]\n", $_, join ',', sort $_ > 0 ? 1..$_ : $_..1) for 13, 21, -22</syntaxhighlight>
{{out}}
{{out}}
<pre> 13: [1,10,11,12,13,2,3,4,5,6,7,8,9]
<pre> 13: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Line 1,023: Line 1,285:
=={{header|Phix}}==
=={{header|Phix}}==
Accepts a proper sequence, in preference to guessing what say a lone 13 actually means, and/or wanting start/stop/step that'd probably just get passed on to tagset() anyway.
Accepts a proper sequence, in preference to guessing what say a lone 13 actually means, and/or wanting start/stop/step that'd probably just get passed on to tagset() anyway.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 1,035: Line 1,297:
<span style="color: #0000FF;">?</span><span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">21</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">21</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1.25</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">11.3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">13</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">lexicographic_order</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1.25</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">11.3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">13</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,047: Line 1,309:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(println
<syntaxhighlight lang="picolisp">(println
(by
(by
format
format
sort
sort
(range 1 13) ) )</lang>
(range 1 13) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,059: Line 1,321:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>lexicographical_sort(Numbers, Sorted_numbers):-
<syntaxhighlight lang="prolog">lexicographical_sort(Numbers, Sorted_numbers):-
number_strings(Numbers, Strings),
number_strings(Numbers, Strings),
sort(Strings, Sorted_strings),
sort(Strings, Sorted_strings),
Line 1,093: Line 1,355:
test(13),
test(13),
test(21),
test(21),
test(-22).</lang>
test(-22).</syntaxhighlight>


{{out}}
{{out}}
Line 1,106: Line 1,368:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{trans|Go}}
{{trans|Go}}
<lang purebasic>EnableExplicit
<syntaxhighlight lang="purebasic">EnableExplicit


Procedure lexOrder(n, Array ints(1))
Procedure lexOrder(n, Array ints(1))
Line 1,149: Line 1,411:
Data.i 0, 5, 13, 21, -22
Data.i 0, 5, 13, 21, -22
EndDataSection
EndDataSection
EndIf</lang>
EndIf</syntaxhighlight>


{{out}}
{{out}}
Line 1,163: Line 1,425:


=={{header|Python}}==
=={{header|Python}}==
<lang python>n=13
<syntaxhighlight lang="python">n=13
print(sorted(range(1,n+1), key=str))</lang>
print(sorted(range(1,n+1), key=str))</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
Line 1,171: Line 1,433:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ [] swap times
<syntaxhighlight lang="quackery"> [ [] swap times
[ i^ 1+ number$
[ i^ 1+ number$
nested join ]
nested join ]
Line 1,179: Line 1,441:
[ $->n drop join ] ] is task ( n --> [ )
[ $->n drop join ] ] is task ( n --> [ )


13 task echo</lang>
13 task echo</syntaxhighlight>


{{out}}
{{out}}
Line 1,188: Line 1,450:
=={{header|Racket}}==
=={{header|Racket}}==


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


(define (lex-sort n) (sort (if (< 0 n) (range 1 (add1 n)) (range n 2))
(define (lex-sort n) (sort (if (< 0 n) (range 1 (add1 n)) (range n 2))
Line 1,200: Line 1,462:
(show 13)
(show 13)
(show 21)
(show 21)
(show -22)</lang>
(show -22)</syntaxhighlight>


{{out}}
{{out}}
Line 1,216: Line 1,478:
{{works with|Rakudo|2018.06}}
{{works with|Rakudo|2018.06}}
It is somewhat odd that the task name is sort '''numbers''' lexicographically but immediately backtracks in the task header to sorting '''integers''' lexicographically. Why only integers? This will sort ANY real numbers lexicographically. For a non-integer, assumes that the given number is a hard boundary and 1 is a "soft" boundary. E.G. The given number is definitely included; 1 is only a threshold, it is included if it matches exactly. (Could be the other way around, this it the way I choose.)
It is somewhat odd that the task name is sort '''numbers''' lexicographically but immediately backtracks in the task header to sorting '''integers''' lexicographically. Why only integers? This will sort ANY real numbers lexicographically. For a non-integer, assumes that the given number is a hard boundary and 1 is a "soft" boundary. E.G. The given number is definitely included; 1 is only a threshold, it is included if it matches exactly. (Could be the other way around, this it the way I choose.)
<lang perl6>sub lex (Real $n, $step = 1) {
<syntaxhighlight lang="raku" line>sub lex (Real $n, $step = 1) {
($n < 1 ?? ($n, * + $step …^ * > 1)
($n < 1 ?? ($n, * + $step …^ * > 1)
!! ($n, * - $step …^ * < 1)).sort: ~*
!! ($n, * - $step …^ * < 1)).sort: ~*
Line 1,225: Line 1,487:
my ($bound, $step) = |$_, 1;
my ($bound, $step) = |$_, 1;
say "Boundary:$bound, Step:$step >> ", lex($bound, $step).join: ', ';
say "Boundary:$bound, Step:$step >> ", lex($bound, $step).join: ', ';
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Boundary:13, Step:1 >> 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
<pre>Boundary:13, Step:1 >> 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
Line 1,237: Line 1,499:
This REXX version allows the starting and ending numbers to be specified via the command line (CL),
This REXX version allows the starting and ending numbers to be specified via the command line (CL),
<br>as well as the increment. &nbsp; Negative numbers are supported and need not be integers.
<br>as well as the increment. &nbsp; Negative numbers are supported and need not be integers.
<lang rexx>/*REXX pgm displays a horizontal list of a range of numbers sorted lexicographically.*/
<syntaxhighlight lang="rexx">/*REXX pgm displays a horizontal list of a range of numbers sorted lexicographically.*/
parse arg LO HI INC . /*obtain optional arguments from the CL*/
parse arg LO HI INC . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
Line 1,260: Line 1,522:
do j=1 for m; k= j+1; if @.j>>@.k then parse value @.j @.k 0 with @.k @.j ok
do j=1 for m; k= j+1; if @.j>>@.k then parse value @.j @.k 0 with @.k @.j ok
end /*j*/ /* [↑] swap 2 elements, flag as ¬done.*/
end /*j*/ /* [↑] swap 2 elements, flag as ¬done.*/
end /*m*/; return</lang>
end /*m*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 1,283: Line 1,545:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Lexicographical numbers
# Project : Lexicographical numbers


Line 1,303: Line 1,565:
svect = left(svect, len(svect) - 1)
svect = left(svect, len(svect) - 1)
see svect + "]" + nl
see svect + "]" + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Lexicographical numbers = [1,10,11,12,13,2,3,4,5,6,7,8,9]
Lexicographical numbers = [1,10,11,12,13,2,3,4,5,6,7,8,9]
</pre>

=={{header|RPL}}==
{{works with|HP|48}}
≪ ≪ n →STR ≫ 'n' 1 4 ROLL 1 SEQ
SORT ≪ STR→ ≫ DOLIST
≫ '<span style="color:blue">LEXICON</span>' STO

13 <span style="color:blue">LEXICON</span>
{{out}}
<pre>
1: { 1 10 11 12 13 2 3 4 5 6 7 8 9 }
</pre>
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>n = 13
<syntaxhighlight lang="ruby">n = 13
p (1..n).sort_by(&:to_s)
p (1..n).sort_by(&:to_s)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
<pre>[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
Line 1,318: Line 1,592:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn lex_sorted_vector(num: i32) -> Vec<i32> {
<syntaxhighlight lang="rust">fn lex_sorted_vector(num: i32) -> Vec<i32> {
let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
Line 1,329: Line 1,603:
println!("{}: {:?}", n, lex_sorted_vector(*n));
println!("{}: {:?}", n, lex_sorted_vector(*n));
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,342: Line 1,616:
=={{header|Scala}}==
=={{header|Scala}}==
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/KpWHYNR/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/BnxJXLjCRvObdOv3VKTtYA Scastie (remote JVM)].
{{Out}}Best seen in running your browser either by [https://scalafiddle.io/sf/KpWHYNR/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/BnxJXLjCRvObdOv3VKTtYA Scastie (remote JVM)].
<lang Scala>object LexicographicalNumbers extends App { def ints = List(0, 5, 13, 21, -22)
<syntaxhighlight lang="scala">object LexicographicalNumbers extends App { def ints = List(0, 5, 13, 21, -22)


def lexOrder(n: Int): Seq[Int] = (if (n < 1) n to 1 else 1 to n).sortBy(_.toString)
def lexOrder(n: Int): Seq[Int] = (if (n < 1) n to 1 else 1 to n).sortBy(_.toString)
Line 1,349: Line 1,623:
for (n <- ints) println(f"$n%3d: ${lexOrder(n).mkString("[",", ", "]")}%s")
for (n <- ints) println(f"$n%3d: ${lexOrder(n).mkString("[",", ", "]")}%s")


}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func lex_order (n) {
<syntaxhighlight lang="ruby">func lex_order (n) {
[range(1, n, n.sgn)...].sort_by { Str(_) }
[range(1, n, n.sgn)...].sort_by { Str(_) }
}
}
Line 1,358: Line 1,632:
[13, 21, -22].each {|n|
[13, 21, -22].each {|n|
printf("%4s: %s\n", n, lex_order(n))
printf("%4s: %s\n", n, lex_order(n))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,369: Line 1,643:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>func lex(n: Int) -> [Int] {
<syntaxhighlight lang="swift">func lex(n: Int) -> [Int] {
return stride(from: 1, through: n, by: n.signum()).map({ String($0) }).sorted().compactMap(Int.init)
return stride(from: 1, through: n, by: n.signum()).map({ String($0) }).sorted().compactMap(Int.init)
}
}
Line 1,375: Line 1,649:
print("13: \(lex(n: 13))")
print("13: \(lex(n: 13))")
print("21: \(lex(n: 21))")
print("21: \(lex(n: 21))")
print("-22: \(lex(n: -22))")</lang>
print("-22: \(lex(n: -22))")</syntaxhighlight>


{{out}}
{{out}}
Line 1,384: Line 1,658:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc iota {num {start 0} {step 1}} {
<syntaxhighlight lang="tcl">proc iota {num {start 0} {step 1}} {
set res {}
set res {}
set end [+ $start [* $step $num]]
set end [+ $start [* $step $num]]
Line 1,393: Line 1,667:
}
}


puts [lsort [iota 13 1]]</lang>
puts [lsort [iota 13 1]]</syntaxhighlight>
{{out}}
{{out}}
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>
<pre>1 10 11 12 13 2 3 4 5 6 7 8 9</pre>


=={{header|VBA}}==
=={{header|VBA}}==
<lang VB>Public Function sortlexicographically(N As Integer)
<syntaxhighlight lang="vb">Public Function sortlexicographically(N As Integer)
Dim arrList As Object
Dim arrList As Object
Set arrList = CreateObject("System.Collections.ArrayList")
Set arrList = CreateObject("System.Collections.ArrayList")
Line 1,413: Line 1,687:
Public Sub main()
Public Sub main()
Call sortlexicographically(13)
Call sortlexicographically(13)
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9, </pre>
<pre>1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9, </pre>
Line 1,419: Line 1,693:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-sort}}
<lang ecmascript>import "/sort" for Sort
<syntaxhighlight lang="wren">import "./sort" for Sort


var a = (1..13).map { |i| "%(i)" }.toList
var a = (1..13).map { |i| "%(i)" }.toList
Sort.quick(a)
Sort.quick(a)
System.print(a)</lang>
System.print(a)</syntaxhighlight>


{{out}}
{{out}}
Line 1,431: Line 1,705:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn lexN(n){ n.pump(List,'+(1),"toString").sort().apply("toInt") }</lang>
<syntaxhighlight lang="zkl">fcn lexN(n){ n.pump(List,'+(1),"toString").sort().apply("toInt") }</syntaxhighlight>
<lang zkl>foreach n in (T(5,13,21)){ println("%2d: %s".fmt(n,lexN(n).concat(","))) }</lang>
<syntaxhighlight lang="zkl">foreach n in (T(5,13,21)){ println("%2d: %s".fmt(n,lexN(n).concat(","))) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 10:57, 8 February 2024

Task
Sort numbers lexicographically
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order.


Show all output here on this page.


Example

Given   13,
return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].

11l

Translation of: Python
V n = 13
print(sorted(Array(1..n), key' i -> String(i)))
Output:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

Action!

PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

INT FUNC Compare(INT a1,a2)
  CHAR ARRAY s1(10),s2(10)
  INT res

  StrI(a1,s1) StrI(a2,s2)
  res=SCompare(s1,s2)
RETURN (res)

PROC InsertionSort(INT ARRAY a INT size)
  INT i,j,value

  FOR i=1 TO size-1
  DO
    value=a(i)
    j=i-1
    WHILE j>=0 AND Compare(a(j),value)>0
    DO
      a(j+1)=a(j)
      j==-1
    OD
    a(j+1)=value
  OD
RETURN

PROC Test(INT ARRAY a INT size)
  PrintE("Array before sort:")
  PrintArray(a,size)
  InsertionSort(a,size)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN

PROC Main()
  DEFINE COUNT_A="13"
  DEFINE COUNT_B="50"
  INT ARRAY a(COUNT_A),b(COUNT_B)
  BYTE i

  FOR i=1 TO COUNT_A
  DO a(i-1)=i OD

  FOR i=1 TO COUNT_B
  DO b(i-1)=i OD

  Test(a,COUNT_A)
  Test(b,COUNT_B)
RETURN
Output:

Screenshot from Atari 8-bit computer

Array before sort:
[1 2 3 4 5 6 7 8 9 10 11 12 13]
Array after sort:
[1 10 11 12 13 2 3 4 5 6 7 8 9]

Array before sort:
[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50]
Array after sort:
[1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 33 34 35 36 37 38 39 4 40 41 42 43 44 45 46 47 48 49 5 50 6 7 8 9]

Ada

WITH Ada.Containers.Generic_Array_Sort, Ada.Text_IO;
USE  Ada.Text_IO;
PROCEDURE Main IS
   TYPE Natural_Array IS ARRAY (Positive RANGE <>) OF Natural;
   FUNCTION Less (L, R : Natural) RETURN Boolean IS (L'Img < R'Img);
   PROCEDURE Sort_Naturals IS NEW Ada.Containers.Generic_Array_Sort
     (Positive, Natural, Natural_Array, Less);
   PROCEDURE Show (Last : Natural) IS
      A : Natural_Array (1 .. Last);
   BEGIN
      FOR I IN A'Range LOOP A (I) := I; END LOOP;
      Sort_Naturals (A);
      FOR I IN  A'Range LOOP Put (A (I)'Img); END LOOP;
      New_Line;
   END Show;
BEGIN
   Show (13);
   Show (21);
END Main;
Output:
 1 10 11 12 13 2 3 4 5 6 7 8 9
 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9
Output:

ALGOL 68

Uses code from the Sorting algorithms/Insertion sort tasl - included here for convenience.

BEGIN # sort numbers lexicographically                                        #

    # code from the Sorting algorithms/Insertion sort task                    #
    MODE DATA = STRING;

    PROC in place insertion sort = (REF[]DATA item)VOID:
    BEGIN
       INT first := LWB item;
       INT last  := UPB item;
       INT j;
       DATA value;
       FOR i FROM first + 1 TO last DO
          value := item[i];
          j := i - 1;
          WHILE ( j >= LWB item AND j <= UPB item | item[j]>value | FALSE ) DO
             item[j + 1] := item[j];
             j -:=  1
          OD;
          item[j + 1] := value
       OD
    END # in place insertion sort #;

    # end code from the Sorting algorithms/Insertion sort task                #

    # returns s converted to an integer, NB: no error checking                #
    OP   TOINT = ( STRING s )INT:
         BEGIN
            INT result := 0;
            FOR i FROM LWB s TO UPB s DO
                result *:= 10 +:= ( ABS s[ i ] - ABS "0" )
            OD;
            result
         END # TOINT # ;

    # returns a array of integers 1..n sorted lexicographically               #
    PROC lexicographic order = ( INT n )[]INT:
         BEGIN
            [ 1 : n ]STRING v; FOR i TO n DO v[ i ] := whole( i, 0 ) OD;
            in place insertion sort( v );
            [ 1 : n ]INT result;
            FOR i TO n DO result[ i ] := TOINT v[ i ] OD;
            result
         END # lexicographic order # ;

    # prints the elements of a                                                #
    PROC show int array = ( []INT a )VOID:
         BEGIN
             print( ( "[" ) );
             FOR i FROM LWB a TO UPB a DO print( ( " ", whole( a[ i ], 0 ) ) ) OD;
             print( ( " ]", newline ) )
         END # show int array # ;

    # test cases                                                              #
    show int array( lexicographic order( 13 ) );
    show int array( lexicographic order( 21 ) )

END
Output:
[ 1 10 11 12 13 2 3 4 5 6 7 8 9 ]
[ 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9 ]

APL

Dyalog APL (with origin 0, ⎕IO←0)

     {⍎¨{⍵[⍋⍵]}⍕¨1+⍳⍵} 13
 1  10  11  12  13  2  3  4  5  6  7  8  9
     {⍎¨{⍵[⍋⍵]}⍕¨1+⍳⍵} 21 
 1  10  11  12  13  14  15  16  17  18  19  2  20  21  3  4  5  6  7  8  9

AppleScript

For fast execution of the task as specified, this take on the BBC BASIC method below generates the integers in the required order:

on oneToNLexicographically(n)
    script o
        property output : {}
        
        on otnl(i)
            set j to i + 9 - i mod 10
            if (j > n) then set j to n
            repeat with i from i to j
                set end of my output to i
                tell i * 10 to if (it  n) then my otnl(it)
            end repeat
        end otnl
    end script
    
    o's otnl(1)
    
    return o's output
end oneToNLexicographically

-- Test code:
oneToNLexicographically(13)
--> {1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}

oneToNLexicographically(123)
--> {1, 10, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 11, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 12, 120, 121, 122, 123, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99}

In the unlikely event of it ever being necessary to sort a given list of integers in this fashion, one possibility is to create another list containing text versions of the integers and to sort this while rearranging the integer versions in parallel.

use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later.
use sorter : script ¬
    "Custom Iterative Ternary Merge Sort" -- <www.macscripter.net/t/timsort-and-nigsort/71383/3>

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

on sortLexicographically(integerList)
    set textList to paragraphs of join(integerList, linefeed)
    -- Sort textList, echoing the moves in integerList.
    considering hyphens but ignoring numeric strings
        tell sorter to sort(textList, 1, -1, {slave:{integerList}})
    end considering
end sortLexicographically

-- Test code:
local someIntegers
set someIntegers to {1, 2, -6, 3, 4, 5, -10, 6, 7, 8, 9, 10, 11, 12, 13, -2, -5, -1, -4, -3, 0}
sortLexicographically(someIntegers)
return someIntegers
Output:
{-1, -10, -2, -3, -4, -5, -6, 0, 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}

Arturo

arr: 1..13
print sort map arr => [to :string &]
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

ATS

The program converts the integers to strings, sorts the strings, then converts the strings back to integers. The method can be used to sort any sequence of non-negative integers.

(Radix sorting the numbers in their original form is another possible approach.)

(* The Rosetta Code lexicographic sort task. *)

#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"

#define NIL list_nil ()
#define ::  list_cons

fn
uint_to_digit (n : uint)
    : char =
  int2char0 (g0u2i n + char2int0 '0')

fn
int_to_string {n : nat}
              (n : int n)
    : string =
  if iseqz n then
    "0"
  else
    let
      fun
      loop {i : nat | i <= 20}
           .<i>.
           (buf : &array (char, 21),
            i   : int i,
            n   : uint)
          : [j : nat | j <= 20]
            int j =
        if (i = 0) + (iseqz n) then
          i
        else
          let
            val i1 = pred i
          in
            buf[i1] := uint_to_digit (n mod 10u);
            loop (buf, i1, n / 10u)
          end

      var buf = @[char][21] ('\0')
      val j = loop (buf, 20, g0i2u n)
      val p = ptr_add<char> (addr@ buf, j)
    in
      strptr2string (string0_copy ($UN.cast{string} p))
    end

fn
iota1 {n : pos}
      (n : int n)
    : list ([i : pos | i <= n] int i, n) =
  let
    typedef t = [i : pos | i <= n] int i

    fun
    loop {i : nat | i <= n}
         .<i>.
         (i     : int i,
          accum : list (t, n - i))
        : list (t, n) =
      if i = 0 then
        accum
      else
        loop (pred i, i :: accum)
  in
    loop (n, NIL)
  end

fn
reverse_map_numbers_to_strings
          {n    : int}
          (nums : list ([i : nat] int i, n))
    : list (string, n) =
  let
    typedef t = [i : nat] int i

    fun
    loop {i : nat | i <= n}
         .<n - i>.
         (nums  : list (t, n - i),
          accum : list (string, i))
        : list (string, n) =
      case+ nums of
      | NIL => accum
      | head :: tail =>
        loop {i + 1} (tail, int_to_string head :: accum)

    prval () = lemma_list_param nums
  in
    loop {0} (nums, NIL)
  end

fn
reverse_map_strings_to_numbers
          {n       : int}
          (strings : list (string, n))
    : list (int, n) =
  let
    macdef string_to_int (s) =
      $extfcall (int, "atoi", ,(s))

    fun
    loop {i : nat | i <= n}
         .<n - i>.
         (strings : list (string, n - i),
          accum   : list (int, i))
        : list (int, n) =
      case+ strings of
      | NIL => accum
      | head :: tail =>
        loop {i + 1} (tail, string_to_int head :: accum)

    prval () = lemma_list_param strings
  in
    loop {0} (strings, NIL)
  end
    
fn
lexicographic_iota1
          {n : pos}
          (n : int n)
    : list (int, n) =
  let
    val numstrings =
      reverse_map_numbers_to_strings (iota1 n)

    (* One could use a MSB-first radix sort here, but I will use what
       is readily available. *)
    implement
    list_mergesort$cmp<string> (x, y) =
      ~compare (x, y)
  in
    reverse_map_strings_to_numbers
      (list_vt2t (list_mergesort<string> numstrings))
  end

implement
main0 () =
  begin
    println! (lexicographic_iota1 13);
    println! (lexicographic_iota1 100)
  end
Output:
$ patscc -DATS_MEMALLOC_GCBDW lexicographic_sort.dats -lgc && ./a.out
1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
1, 10, 100, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 6, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 7, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

AutoHotkey

n2lexicog(n){
    Arr := [], list := ""
    loop % n
        list .= A_Index "`n"
    Sort, list
    for k, v in StrSplit(Trim(list, "`n"), "`n")
        Arr.Push(v)
    return Arr
}

Examples:

n := 13
x := n2lexicog(n)
for k, v in x
    output .= v ", "
MsgBox % "[" Trim(output, ", ") "]"					; show output
return
Output:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

AWK

Robust with checks

# syntax: GAWK -f SORT_NUMBERS_LEXICOGRAPHICALLY.AWK
#
# sorting:
#   PROCINFO["sorted_in"] is used by GAWK
#   SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
    prn(0)
    prn(1)
    prn(13)
    prn(9,10)
    prn(-11,+11)
    prn(-21)
    prn("",1)
    prn(+1,-1)
    exit(0)
}
function prn(n1,n2) {
    if (n1 <= 0 && n2 == "") {
      n2 = 1
    }
    if (n2 == "") {
      n2 = n1
      n1 = 1
    }
    printf("%d to %d: %s\n",n1,n2,snl(n1,n2))
}
function snl(start,stop,  arr,i,str) {
    if (start == "") {
      return("error: start=blank")
    }
    if (start > stop) {
      return("error: start>stop")
    }
    for (i=start; i<=stop; i++) {
      arr[i]
    }
    PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 2
    for (i in arr) {
      str = sprintf("%s%s ",str,i)
    }
    sub(/ $/,"",str)
    return(str)
}
Output:
0 to 1: 0 1
1 to 1: 1
1 to 13: 1 10 11 12 13 2 3 4 5 6 7 8 9
9 to 10: 10 9
-11 to 11: -1 -10 -11 -2 -3 -4 -5 -6 -7 -8 -9 0 1 10 11 2 3 4 5 6 7 8 9
-21 to 1: -1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -3 -4 -5 -6 -7 -8 -9 0 1
0 to 1: error: start=blank
1 to -1: error: start>stop

Alternative, using GAWK's builtin sort

This version explicitly casts integers as strings during list generation and uses the builtin sort available in GAWK on element values.

BEGIN {
    n=13
    for (i=1; i<=n; i++) 
        a[i]=i""
    asort(a)
    for (k in a)
        printf "%d ", a[k]
}
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9 

BaCon

Create a delimited string with numbers and use SORT$.

CONST n = 13
FOR x = 1 TO n
    result$ = APPEND$(result$, 0, STR$(x))
NEXT
PRINT SORT$(result$)
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

BBC BASIC

      N%=13
      PRINT "[" LEFT$(FNLexOrder(0)) "]"
      END

      DEF FNLexOrder(nr%) : LOCAL i%, s$
      FOR i%=nr% TO nr% + 9
        IF i% > N% EXIT FOR
        IF i% > 0 s$+=STR$i% + "," + FNLexOrder(i% * 10)
      NEXT
      =s$
Output:
[1,10,11,12,13,2,3,4,5,6,7,8,9]

BQN

Task  (•Fmt¨)1+↕

Task 13
Output:
⟨ 1 10 11 12 13 2 3 4 5 6 7 8 9 ⟩

C

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compareStrings(const void *a, const void *b) {
    const char **aa = (const char **)a;
    const char **bb = (const char **)b;
    return strcmp(*aa, *bb);
}

void lexOrder(int n, int *ints) {
    char **strs;
    int i, first = 1, last = n, k = n, len;
    if (n < 1) {
        first = n; last = 1; k = 2 - n;
    } 
    strs = malloc(k * sizeof(char *));
    for (i = first; i <= last; ++i) {
        if (i >= 1) len = (int)log10(i) + 2;
        else if (i == 0) len = 2;
        else len = (int)log10(-i) + 3; 
        strs[i-first] = malloc(len);
        sprintf(strs[i-first], "%d", i);
    }
    qsort(strs, k, sizeof(char *), compareStrings);
    for (i = 0; i < k; ++i) {
        ints[i] = atoi(strs[i]);
        free(strs[i]);
    }
    free(strs);
}

int main() {
    int i, j, k, n,  *ints;
    int numbers[5] = {0, 5, 13, 21, -22};
    printf("In lexicographical order:\n\n");
    for (i = 0; i < 5; ++i) {
        k = n = numbers[i];
        if (k < 1) k = 2 - k;
        ints = malloc(k * sizeof(int));
        lexOrder(n, ints);
        printf("%3d: [", n);
        for (j = 0; j < k; ++j) {
            printf("%d ", ints[j]);
        }
        printf("\b]\n");
        free(ints);
    }
    return 0;
}
Output:
In lexicographical order:

  0: [0 1]
  5: [1 2 3 4 5]
 13: [1 10 11 12 13 2 3 4 5 6 7 8 9]
 21: [1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
-22: [-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1]

C#

Works with: C sharp version 7
using static System.Console;
using static System.Linq.Enumerable;

public class Program
{
    public static void Main() {
        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
    }

    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}
Output:
0: 0, 1
5: 1, 2, 3, 4, 5
13: 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
21: 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9
-22: -1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1

C++

#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

void lexicographical_sort(std::vector<int>& numbers) {
    std::vector<std::string> strings(numbers.size());
    std::transform(numbers.begin(), numbers.end(), strings.begin(),
                   [](int i) { return std::to_string(i); });
    std::sort(strings.begin(), strings.end());
    std::transform(strings.begin(), strings.end(), numbers.begin(),
                   [](const std::string& s) { return std::stoi(s); });
}

std::vector<int> lexicographically_sorted_vector(int n) {
    std::vector<int> numbers(n >= 1 ? n : 2 - n);
    std::iota(numbers.begin(), numbers.end(), std::min(1, n));
    lexicographical_sort(numbers);
    return numbers;
}

template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
    out << '[';
    if (!v.empty()) {
        auto i = v.begin();
        out << *i++;
        for (; i != v.end(); ++i)
            out << ',' << *i;
    }
    out << "]\n";
}

int main(int argc, char** argv) {
    for (int i : { 0, 5, 13, 21, -22 }) {
        std::cout << i << ": ";
        print_vector(std::cout, lexicographically_sorted_vector(i));
    }
    return 0;
}
Output:
0: [0,1]
5: [1,2,3,4,5]
13: [1,10,11,12,13,2,3,4,5,6,7,8,9]
21: [1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9]
-22: [-1,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-2,-20,-21,-22,-3,-4,-5,-6,-7,-8,-9,0,1]

Clojure

(def n 13)
(sort-by str (range 1 (inc n)))
Output:
(1 10 11 12 13 2 3 4 5 6 7 8 9)

COBOL

Works with: GnuCOBOL
       identification division.
       program-id. LexicographicalNumbers.

       data division.
       working-storage section.
       78  MAX-NUMBERS            value 21.
       77  i                      pic 9(2).
       77  edited-number          pic z(2).
       
       01  lex-table.
           05 table-itms occurs MAX-NUMBERS.
              10 number-lex       pic x(2).

       procedure division.
       main.
      *>-> Load numbers
           perform varying i from 1 by 1 until i > MAX-NUMBERS
              move i to edited-number
              move edited-number to number-lex(i)
              call "C$JUSTIFY" using number-lex(i), "Left"
           end-perform

      *>-> Sort in lexicographic order
           sort table-itms ascending number-lex

      *>-> Show ordered numbers
           display "[" no advancing
           perform varying i from 1 by 1 until i > MAX-NUMBERS
              display function trim(number-lex(i)) no advancing
              if i < MAX-NUMBERS
                 display ", " no advancing
              end-if
           end-perform
           display "]"
           stop run
           .
Output:
[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]

Common Lisp

(defun lexicographic-sort (n)
  (sort (alexandria:iota n :start 1) #'string<= :key #'write-to-string))
(lexicographic-sort 13)
Output:
(1 10 11 12 13 2 3 4 5 6 7 8 9)

Factor

USING: formatting kernel math.parser math.ranges sequences
sorting ;
IN: rosetta-code.lexicographical-numbers

: lex-order ( n -- seq )
    [1,b] [ number>string ] map natural-sort
    [ string>number ] map ;
    
{ 13 21 -22 } [ dup lex-order "%3d: %[%d, %]\n" printf ] each
Output:
 13: { 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9 }
 21: { 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9 }
-22: { -1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1 }

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Test case

FreeBASIC

function leq( n as integer, m as integer ) as boolean
    if str(n)<=str(m) then return true else return false
end function

sub shellsort(s() as integer)
    dim as integer n = ubound(s)
    dim as integer i, inc = n
    dim as boolean done
 
    do
        inc\=2.2
        if inc = 0 then inc = 1
        do
            done = false
            for i = 0 to n - inc
                if leq(s(i+inc), s(i)) then
                    swap s(i), s(i + inc)
                    done = true
                end if
            next
        loop until done = 0
    loop until inc = 1
end sub

dim as integer n, i

input n

dim as integer s(0 to n-1)
for i = 0 to n-1
    s(i) = i+1
next i

shellsort(s())

print "[";
for i = 0 to n-1
    print s(i);
    if i<n-1 then print ", ";
next i
print "]"
Output:

? 13 [ 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

Go

package main

import (
    "fmt"
    "sort"
    "strconv"
)

func lexOrder(n int) []int {
    first, last, k := 1, n, n
    if n < 1 {
        first, last, k = n, 1, 2-n
    }
    strs := make([]string, k)
    for i := first; i <= last; i++ {
        strs[i-first] = strconv.Itoa(i)
    }
    sort.Strings(strs)
    ints := make([]int, k)
    for i := 0; i < k; i++ {
        ints[i], _ = strconv.Atoi(strs[i])
    }
    return ints
}

func main() {
    fmt.Println("In lexicographical order:\n")
    for _, n := range []int{0, 5, 13, 21, -22} {
        fmt.Printf("%3d: %v\n", n, lexOrder(n))
    }
}
Output:
In lexicographical order:

  0: [0 1]
  5: [1 2 3 4 5]
 13: [1 10 11 12 13 2 3 4 5 6 7 8 9]
 21: [1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
-22: [-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1]

Haskell

import Data.List (sort)

task :: (Ord b, Show b) => [b] -> [b]
task = map snd . sort . map (\i -> (show i, i))

main = print $ task [1 .. 13]

Which we could also write, in a point-free style as:

import Data.List (sort)

task
  :: (Ord b, Show b)
  => [b] -> [b]
task = map snd . sort . map (show >>= (,))

main = print $ task [1 .. 13]

and the simplest approach might be sortOn show (which only evaluates show once for each item).

import Data.List (sortOn)

main :: IO ()
main = print $ sortOn show [1 .. 13]
Output:
[1,10,11,12,13,2,3,4,5,6,7,8,9]

Isabelle

Works with: Isabelle version 2020
theory LexList
  imports
    Main 
    "~~/src/HOL/Library/Char_ord" 
    "~~/src/HOL/Library/List_Lexorder"
begin

definition ord_ascii_zero :: nat where
  "ord_ascii_zero == of_char (CHR ''0'')"

text‹Get the string representation for a single digit.›
definition ascii_of_digit :: "nat ⇒ string" where
  "ascii_of_digit n ≡ if n ≥ 10 then undefined else [char_of (n + ord_ascii_zero)]"

fun ascii_of :: "nat ⇒ string" where
  "ascii_of n = (if n < 10
                  then ascii_of_digit n
                  else ascii_of (n div 10) @ ascii_of_digit (n mod 10))"

lemma ‹ascii_of 123 = ''123''› by code_simp

value ‹sort (map ascii_of (upt 1 13))›
end
Output:
"[''1'', ''10'', ''11'', ''12'', ''2'', ''3'', ''4'', ''5'', ''6'', ''7'', ''8'', ''9'']"
  :: "char list list"

J

task=: [: (/: ":"0) 1 + i.
task 13
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

Java

Translation of: Kotlin


Requires Java 8 or later.

import java.util.List;
import java.util.stream.*;

public class LexicographicalNumbers {

    static List<Integer> lexOrder(int n) {
        int first = 1, last = n;
        if (n < 1) {
            first = n;
            last = 1;
        }
        return IntStream.rangeClosed(first, last)
                        .mapToObj(Integer::toString)
                        .sorted()
                        .map(Integer::valueOf)
                        .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        System.out.println("In lexicographical order:\n");
        int[] ints = {0, 5, 13, 21, -22};
        for (int n : ints) {
           System.out.printf("%3d: %s\n", n, lexOrder(n));
        }
    }
}
Output:
In lexicographical order:

  0: [0, 1]
  5: [1, 2, 3, 4, 5]
 13: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
 21: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]

K

task: 1+<$1+!:

task 13
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

Ksh

#!/bin/ksh

# Sort numbers lexicographically

#	# Variables:
#
integer N=${1:-13}

#	# Functions:
#

#	# Function _fillarray(arr, N) - fill assoc. array 1 -> N
#
function _fillarray {
	typeset _arr ; nameref _arr="$1"
	typeset _N ; integer _N=$2
	typeset _i _st _en ; integer _i _st _en

	(( ! _N )) && _arr=0 && return
	(( _N<0 )) && _st=${_N} && _en=1
	(( _N>0 )) && _st=1 && _en=${_N}

	for ((_i=_st; _i<=_en; _i++)); do
		_arr[${_i}]=${_i}
	done
}

 ######
# main #
 ######

set -a -s -A arr
typeset -A arr
_fillarray arr ${N}

print -- ${arr[*]}
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

jq

Works with: jq

Works with gojq, the Go implementation of jq

def sort_range($a;$b): [range($a;$b)] | sort_by(tostring);

# Example
# jq's index origin is 0, so ...
sort_range(1;14)
Output:
[1,10,11,12,13,2,3,4,5,6,7,8,9]

Julia

lexorderedsequence(n) = sort(collect(n > 0 ? (1:n) : n:1), lt=(a,b) -> string(a) < string(b))

for i in [0, 5, 13, 21, -32]
    println(lexorderedsequence(i))
end
Output:
[0, 1]
[1, 2, 3, 4, 5]
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
[-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -3, -30, -31, -32, -4, -5, -6, -7, -8, -9, 0, 1]

Kotlin

// Version 1.2.51

fun lexOrder(n: Int): List<Int> {
    var first = 1
    var last = n
    if (n < 1) {
        first = n
        last = 1
    }
    return (first..last).map { it.toString() }.sorted().map { it.toInt() }
}

fun main(args: Array<String>) {
    println("In lexicographical order:\n")
    for (n in listOf(0, 5, 13, 21, -22)) {
        println("${"%3d".format(n)}: ${lexOrder(n)}")
    }
}
Output:
In lexicographical order:

  0: [0, 1]
  5: [1, 2, 3, 4, 5]
 13: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
 21: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]

Lambdatalk

1) lexicographically sorting a sequence of numbers
{S.sort before 1 2 3 4 5 6 7 8 9 10 11 12 13}
-> 1 10 11 12 13 2 3 4 5 6 7 8 9

2) lexicographically sorting an array of numbers
{A.sort! before {A.new 1 2 3 4 5 6 7 8 9 10 11 12 13}}
-> [1,10,11,12,13,2,3,4,5,6,7,8,9]

Lua

Lua's in-built table.sort function will sort a table of strings into lexicographical order by default. This task therefore becomes trivial by converting each number to a string before adding it to the table.

function lexNums (limit)
  local numbers = {}
  for i = 1, limit do
    table.insert(numbers, tostring(i))
  end
  table.sort(numbers)
  return numbers
end

local numList = lexNums(13)
print(table.concat(numList, " "))
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

M2000 Interpreter

Module Checkit {
      Function lexicographical(N) {
            const nl$=Chr$(13)+Chr$(10)
            If N<>0 then {
                  if N=1 then =(1,) : Exit
                  Document A$
                  For k=1 to N-1 
                        A$=Str$(k,"")+{
                        }
                  Next k
                  A$=Str$(N,"")
                  Method A$, "SetBinaryCompare"
                  Sort A$
                  Flush
                  \\ convert strings to numbers in one statement
                  \\ in stack of values
                  Data Param(Replace$(nl$,",", a$))
                  \\ return stack as array 
                  =Array([])
            }  else =(0,)   ' empty array
      }
      Print lexicographical(5)  ' 1 2 3 4 5
      Print lexicographical(13) ' 1 10 11 12 13 2 3 4 5 6 7 8 9
      Print lexicographical(21) ' 1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9
      Print lexicographical(-22) ' -1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1
}
Checkit
Module Checkit {
      Function lexicographical$(N) {
            const nl$=Chr$(13)+Chr$(10)
            If N<>0 then {
                  if N=1 then =(1,) : Exit
                  Document A$
                  For k=1 to N-1 
                        A$=Str$(k,"")+{
                        }
                  Next k
                  A$=Str$(N,"")
                  \\ by default id TextCompare, so 0 an 1 comes first in -22
                  Method A$, "SetBinaryCompare"
                  Sort A$
                  Flush
                  ="["+Replace$(nl$," ", a$)+"]"
                  
            }  else =("",)   ' empty array
      }
      Print lexicographical$(5)  ' [1 2 3 4 5]
      Print lexicographical$(13) ' [1 10 11 12 13 2 3 4 5 6 7 8 9]
      Print lexicographical$(21) '[1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
      Print lexicographical$(-22) ' [-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1]
}
Checkit

Mathematica/Wolfram Language

SortBy[Range[13],ToString]
Output:
{1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9}

Microsoft Small Basic

In Small Basic there is no string comparison: “a”>”b” the result is “False”, “b”>”a” the result is also “False”. It doesn’t help at all.

' Lexicographical numbers - 25/07/2018
xx="000000000000000"
For n=1 To 3
  nn=Text.GetSubText("   5  13  21",n*4-3,4)
  ll=Text.GetLength(nn)
  For i=1 To nn
    t[i]=i
  EndFor
  i=nn-1
  k=0
  For i=i To 1 Step -1
    ok=1
    For j=1 To i
      k=j+1
      tj=Text.GetSubText(Text.Append(t[j],xx),1,ll)
      tk=Text.GetSubText(Text.Append(t[k],xx),1,ll)
      If tj>tk Then 
        w=t[j]
        t[j]=t[k]
        t[k]=w
        ok=0
      EndIf
    EndFor
    If ok=1 Then
      Goto exitfor
    EndIf
  EndFor
exitfor:
  x=""
  For i=1 To nn
    x=x+","+t[i]
  EndFor
  TextWindow.WriteLine(nn+":"+Text.GetSubTextToEnd(x,2))
EndFor
Output:
  5:1,2,3,4,5
 13:1,10,11,12,13,2,3,4,5,6,7,8,9
 21:1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9

MiniScript

Output from REPL.

Output:
> n = 13
> rng = range(1, 13)
> rng.join(" ").split(" ").sort
["1", "10", "11", "12", "13", "2", "3", "4", "5", "6", "7", "8", "9"]

MUMPS

This shows a few unique features of MUMPS:

- There is only one datatype which is implicitly coerced to string, integer, or floating-point as necessary.

- MUMPS arrays sort automatically

- The condensed version shows that there are no reserved keywords

SortLexographically(n)
 new array,i,j
 for i=1:1:n set array(i_" ")=""
 for  set j=$order(array(j)) quit:j=""  write j
 quit

This could also be written:

SortLexographically(n) n a,i,j f i=1:1:n s a(i_" ")="" 
 f  s j=$o(a(j)) q:j=""  w j 
 q
Usage
 do SortLexographically(13)
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

Nim

import algorithm, sequtils

for n in [0, 5, 13, 21, -22]:
  let s = if n > 1: toSeq(1..n) else: toSeq(countdown(1, n))
  echo s.sortedByIt($it)
Output:
@[0, 1]
@[1, 2, 3, 4, 5]
@[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
@[1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
@[-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]

Perl

printf("%4d: [%s]\n", $_, join ',', sort $_ > 0 ? 1..$_ : $_..1) for 13, 21, -22
Output:
  13: [1,10,11,12,13,2,3,4,5,6,7,8,9]
  21: [1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9]
 -22: [-1,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-2,-20,-21,-22,-3,-4,-5,-6,-7,-8,-9,0,1]

Phix

Accepts a proper sequence, in preference to guessing what say a lone 13 actually means, and/or wanting start/stop/step that'd probably just get passed on to tagset() anyway.

with javascript_semantics
function lexicographic_order(sequence s) 
    return extract(s,custom_sort(apply(s,sprint),tagset(length(s))))
end function
 
?lexicographic_order({1,0})
?lexicographic_order(tagset(5))
?lexicographic_order(tagset(13))
?lexicographic_order(tagset(21,1,2))
?lexicographic_order(tagset(11,-21,4))
?lexicographic_order({1.25, -6, -10, 9, -11.3, 13, -3, 0})
Output:
{0,1}
{1,2,3,4,5}
{1,10,11,12,13,2,3,4,5,6,7,8,9}
{1,11,13,15,17,19,21,3,5,7,9}
{-1,-13,-17,-21,-5,-9,11,3,7}
{-10,-11.3,-3,-6,0,1.25,13,9}

PicoLisp

(println
   (by
      format
      sort
      (range 1 13) ) )
Output:
(1 10 11 12 13 2 3 4 5 6 7 8 9)

Prolog

Works with: SWI Prolog
lexicographical_sort(Numbers, Sorted_numbers):-
    number_strings(Numbers, Strings),
    sort(Strings, Sorted_strings),
    number_strings(Sorted_numbers, Sorted_strings).

number_strings([], []):-!.
number_strings([Number|Numbers], [String|Strings]):-
    number_string(Number, String),
    number_strings(Numbers, Strings).

number_list(From, To, []):-
    From > To,
    !.
number_list(From, To, [From|Rest]):-
    Next is From + 1,
    number_list(Next, To, Rest).

lex_sorted_number_list(Number, List):-
    (Number < 1 ->
        number_list(Number, 1, Numbers)
        ;
        number_list(1, Number, Numbers)
    ),
    lexicographical_sort(Numbers, List).

test(Number):-
    lex_sorted_number_list(Number, List),
    writef('%w: %w\n', [Number, List]).

main:-
    test(0),
    test(5),
    test(13),
    test(21),
    test(-22).
Output:
0: [0,1]
5: [1,2,3,4,5]
13: [1,10,11,12,13,2,3,4,5,6,7,8,9]
21: [1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9]
-22: [-1,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-2,-20,-21,-22,-3,-4,-5,-6,-7,-8,-9,0,1]

PureBasic

Translation of: Go
EnableExplicit

Procedure lexOrder(n, Array ints(1))
    Define first = 1, last = n, k = n, i  
    If n < 1
        first = n
        last = 1
        k = 2 - n
    EndIf
    Dim strs.s(k - 1)
    For i = first To last
        strs(i - first) = Str(i)
    Next
    SortArray(strs(), #PB_Sort_Ascending)
    For i = 0 To k - 1
        ints(i) = Val(Strs(i))
    Next
EndProcedure

If OpenConsole()
    PrintN(~"In lexicographical order:\n")
    Define i, j, n, k
    For i = 0 To 4
        Read n
        k = n
        If n < 1
            k = 2 - n
        EndIf
        Dim ints(k - 1)
        lexOrder(n, ints())
        Define.s ns = RSet(Str(n), 3)
        Print(ns + ": [")
        For j = 0 To k - 1
            Print(Str(ints(j)) + " ")
        Next j
        PrintN(~"\b]")
    Next i
    Input()
    End

    DataSection
        Data.i 0, 5, 13, 21, -22
    EndDataSection
EndIf
Output:
In lexicographical order:

  0: [0 1]
  5: [1 2 3 4 5]
 13: [1 10 11 12 13 2 3 4 5 6 7 8 9]
 21: [1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
-22: [-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1]

Python

n=13
print(sorted(range(1,n+1), key=str))
Output:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

Quackery

  [ [] swap times 
      [ i^ 1+ number$ 
        nested join ] 
    sort$ 
    [] swap 
    witheach 
      [ $->n drop join ] ] is task ( n --> [ )

  13 task echo
Output:
[ 1 10 11 12 13 2 3 4 5 6 7 8 9 ]


Racket

#lang racket

(define (lex-sort n) (sort (if (< 0 n) (range 1 (add1 n)) (range n 2))
                           string<? #:key number->string))

(define (show n) (printf "~a: ~a\n" n (lex-sort n)))

(show 0)
(show 1)
(show 5)
(show 13)
(show 21)
(show -22)
Output:
0: (0 1)
1: (1)
5: (1 2 3 4 5)
13: (1 10 11 12 13 2 3 4 5 6 7 8 9)
21: (1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9)
-22: (-1 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -2 -20 -21 -22 -3 -4 -5 -6 -7 -8 -9 0 1)

Raku

(formerly Perl 6)

Works with: Rakudo version 2018.06

It is somewhat odd that the task name is sort numbers lexicographically but immediately backtracks in the task header to sorting integers lexicographically. Why only integers? This will sort ANY real numbers lexicographically. For a non-integer, assumes that the given number is a hard boundary and 1 is a "soft" boundary. E.G. The given number is definitely included; 1 is only a threshold, it is included if it matches exactly. (Could be the other way around, this it the way I choose.)

sub lex (Real $n, $step = 1) {
    ($n < 1 ?? ($n, * + $step …^ * > 1)
            !! ($n, * - $step …^ * < 1)).sort: ~*
}

# TESTING
for 13, 21, -22, (6, .333), (-4, .25), (-5*π, e) {
    my ($bound, $step) = |$_, 1;
    say "Boundary:$bound, Step:$step >> ", lex($bound, $step).join: ', ';
}
Output:
Boundary:13, Step:1 >> 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9
Boundary:21, Step:1 >> 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9
Boundary:-22, Step:1 >> -1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1
Boundary:6, Step:0.333 >> 1.005, 1.338, 1.671, 2.004, 2.337, 2.67, 3.003, 3.336, 3.669, 4.002, 4.335, 4.668, 5.001, 5.334, 5.667, 6
Boundary:-4, Step:0.25 >> -0.25, -0.5, -0.75, -1, -1.25, -1.5, -1.75, -2, -2.25, -2.5, -2.75, -3, -3.25, -3.5, -3.75, -4, 0, 0.25, 0.5, 0.75, 1
Boundary:-15.707963267948966, Step:2.718281828459045 >> -10.271399611030876, -12.989681439489921, -15.707963267948966, -2.116554125653742, -4.834835954112787, -7.553117782571832, 0.6017277028053032

REXX

This REXX version allows the starting and ending numbers to be specified via the command line (CL),
as well as the increment.   Negative numbers are supported and need not be integers.

/*REXX pgm displays a horizontal list of a  range of numbers  sorted  lexicographically.*/
parse arg LO HI INC .                            /*obtain optional arguments from the CL*/
if  LO=='' |  LO==","  then  LO=  1              /*Not specified?  Then use the default.*/
if  HI=='' |  HI==","  then  HI= 13              /* "      "         "   "   "     "    */
if INC=='' | INC==","  then INC=  1              /* "      "         "   "   "     "    */
#= 0                                             /*for actual sort, start array with  1.*/
                  do j=LO  to  HI  by  INC       /*construct an array from  LO   to  HI.*/
                  #= # + 1;        @.#= j / 1    /*bump counter;  define array element. */
                  end   /*j*/                    /* [↑]  Also, normalize the element #. */
call Lsort #                                     /*sort numeric array with a simple sort*/
$=                                               /*initialize a horizontal numeric list.*/
                  do k=1  for  #;    $= $','@.k  /*construct      "         "      "    */
                  end   /*k*/                    /* [↑]  prefix each number with a comma*/
                                                 /* [↓]  display a continued  SAY  text.*/
say 'for   '  LO"──►"HI     ' by '     INC     " (inclusive), "         # ,
                                               ' elements sorted lexicographically:'
say  '['strip($, "L", ',')"]"                    /*strip leading comma, bracket the list*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Lsort: procedure expose @.; parse arg n;  m= n-1 /*N: is the number of @ array elements.*/
       do m=m  by -1  until ok;          ok= 1   /*keep sorting the  @ array until done.*/
          do j=1  for m;  k= j+1;  if @.j>>@.k  then parse value @.j @.k 0 with @.k @.j ok
          end   /*j*/                            /* [↑]  swap 2 elements, flag as ¬done.*/
       end      /*m*/;    return
output   when using the default inputs:
for    1──►13  by  1  (inclusive),  13  elements sorted lexicographically:
[1,10,11,12,13,2,3,4,5,6,7,8,9]
output   when using the input of:     1   34
for    1──►34  by  1  (inclusive),  34  elements sorted lexicographically:
[1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,4,5,6,7,8,9]
output   when using the input of:     -11   22
for    -11──►22  by  1  (inclusive),  34  elements sorted lexicographically:
[-1,-10,-11,-2,-3,-4,-5,-6,-7,-8,-9,0,1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,3,4,5,6,7,8,9]
output   when using the input of:     -4   8   0.5
for    -4──►8  by  0.5  (inclusive),  25  elements sorted lexicographically:
[-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8]

Ring

# Project : Lexicographical numbers

lex = 1:13
strlex = list(len(lex))
for n = 1 to len(lex)
     strlex[n] = string(lex[n])
next
strlex = sort(strlex)
see "Lexicographical numbers = "
showarray(strlex)

func showarray(vect)
        see "["
        svect = ""
        for n = 1 to len(vect)
              svect = svect + vect[n] + ","
        next
        svect = left(svect, len(svect) - 1)
        see svect + "]" + nl

Output:

Lexicographical numbers = [1,10,11,12,13,2,3,4,5,6,7,8,9]

RPL

Works with: HP version 48
≪ ≪ n →STR ≫ 'n' 1 4 ROLL 1 SEQ
   SORT ≪ STR→ ≫ DOLIST
≫ 'LEXICON' STO
13 LEXICON
Output:
1: { 1 10 11 12 13 2 3 4 5 6 7 8 9 }

Ruby

n = 13
p (1..n).sort_by(&:to_s)
Output:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

Rust

fn lex_sorted_vector(num: i32) -> Vec<i32> {
    let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
    let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
    str.sort();
    str.iter().map(|s| s.parse::<i32>().unwrap()).collect()
}

fn main() {
    for n in &[0, 5, 13, 21, -22] {
        println!("{}: {:?}", n, lex_sorted_vector(*n));
    }
}
Output:
0: [0, 1]
5: [1, 2, 3, 4, 5]
13: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
21: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]

Scala

Output:

Best seen in running your browser either by ScalaFiddle (ES aka JavaScript, non JVM) or Scastie (remote JVM).

object LexicographicalNumbers extends App {  def ints = List(0, 5, 13, 21, -22)

  def lexOrder(n: Int): Seq[Int] = (if (n < 1) n to 1 else 1 to n).sortBy(_.toString)

  println("In lexicographical order:\n")
  for (n <- ints) println(f"$n%3d: ${lexOrder(n).mkString("[",", ", "]")}%s")

}

Sidef

func lex_order (n) {
    [range(1, n, n.sgn)...].sort_by { Str(_) }
}

[13, 21, -22].each {|n|
    printf("%4s: %s\n", n, lex_order(n))
}
Output:
  13: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
  21: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
 -22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]


Swift

func lex(n: Int) -> [Int] {
  return stride(from: 1, through: n, by: n.signum()).map({ String($0) }).sorted().compactMap(Int.init)
}

print("13: \(lex(n: 13))")
print("21: \(lex(n: 21))")
print("-22: \(lex(n: -22))")
Output:
13: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
21: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9]
-22: [-1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1]

Tcl

proc iota {num {start 0} {step 1}} {
	set res {}
	set end [+ $start [* $step $num]]
	for {set n $start} {$n != $end} {incr n $step} {
		lappend res $n
	}
	return $res
}

puts [lsort [iota 13 1]]
Output:
1 10 11 12 13 2 3 4 5 6 7 8 9

VBA

Public Function sortlexicographically(N As Integer)
    Dim arrList As Object
    Set arrList = CreateObject("System.Collections.ArrayList")
    For i = 1 To N
        arrList.Add CStr(i)
    Next i
    arrList.Sort
    Dim item As Variant
    For Each item In arrList
        Debug.Print item & ", ";
    Next
End Function

Public Sub main()
    Call sortlexicographically(13)
End Sub
Output:
1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9, 

Wren

Library: Wren-sort
import "./sort" for Sort

var a = (1..13).map { |i| "%(i)" }.toList
Sort.quick(a)
System.print(a)
Output:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

zkl

fcn lexN(n){ n.pump(List,'+(1),"toString").sort().apply("toInt") }
foreach n in (T(5,13,21)){ println("%2d: %s".fmt(n,lexN(n).concat(","))) }
Output:
 5: 1,2,3,4,5
13: 1,10,11,12,13,2,3,4,5,6,7,8,9
21: 1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9