Sorting in Wolfram Language

Our first example demonstrates sorting for built-in types in Wolfram Language. We’ll look at sorting for strings and numbers.

(* Sorting strings *)
strs = {"c", "a", "b"};
sortedStrs = Sort[strs];
Print["Strings: ", sortedStrs]

(* Sorting integers *)
ints = {7, 2, 4};
sortedInts = Sort[ints];
Print["Ints:    ", sortedInts]

(* Checking if a list is sorted *)
isSorted = OrderedQ[sortedInts];
Print["Sorted:  ", isSorted]

To run this program, you can copy it into a Mathematica notebook and evaluate the cells, or save it as a .wl file and run it using the Wolfram kernel.

(* Output *)
Strings: {a, b, c}
Ints:    {2, 4, 7}
Sorted:  True

In Wolfram Language, the Sort function is used to sort lists of various types. It works with many built-in types, including strings and numbers. The sorting is done in ascending order by default.

The OrderedQ function is used to check if a list is already in sorted order. It returns True if the list is sorted in ascending order, and False otherwise.

Note that unlike some other languages, Wolfram Language typically doesn’t modify lists in-place. Instead, functions like Sort return a new sorted list, leaving the original list unchanged.

Wolfram Language’s sorting capabilities are quite powerful and can be customized using various options and comparison functions for more complex sorting scenarios.