To sort words lexicographically according to some alphabet, one can use SortBy
where the key used for a given word is a list of the ranks of its letters in the given alphabet. Lookup
deals with unknown letters; I've supplied the default argument 0
which means unknown letters are before everything else in the alphabet. I also PadRight
to a given length because Mathematica sorts {5}
before {1, 2, 3}
.
ClearAll[SortByAlphabet];
SortByAlphabet[words : {___String}, alphabet : {___String}] :=
With[{
letterranks = Association[Table[alphabet[[i]] -> i,
{i, Length[alphabet]}]],
length = Max[StringLength /@ words]},
SortBy[words,
PadRight[
Lookup[letterranks, Characters[ToLowerCase[#]], 0],
length] &]];
then use for instance as
SortByAlphabet[{"hello", "world", "this", "code", "is",
"in", "mathematica", "or", "perhaps", "i", "should",
"call", "that", "the", "wolfram", "language"},
Join[CharacterRange["n", "z"], CharacterRange["a", "m"]]]
Result:
{"or", "perhaps", "should", "that", "the", "this",
"world", "wolfram", "code", "call", "hello", "i",
"in", "is", "language", "mathematica"}