Sort.Imagine a million lines of text. With no sorting it is impossible to find a certain line. But with sorting it can be easily located.
First example.Here we introduce an array called "patterns" that has 3 strings in it. We then invoke sort() on our patterns array.
Result: The array's elements are reordered. The string "abc" comes first as it is the earliest alphabetically.
Modifies in-place.We can assign a variable to the result of sort() but there is no point to this. Sort() modifies the existing array.
Tip: To keep the originally-ordered array around, a copy of the array would need to be made.
Here: We override the default sorting behavior with a function. In our function "compare" we sort two integers by their difference.
So: Numbers are sorted by their numeric values, and smaller numbers precede larger ones.
LocaleCompare.The localeCompare method handles non-ASCII characters (like those with accents) in a correct way. It should be used when sorting strings.
Here: We use localCompare to sort a string array from low to high (in ascending alphabetical order).
Then: We use a descending string sort. We compare the second string to the first in reverseAlphabetical.
Tip: It is possible to call reverse() after sorting a string array. But with localeCompare we can directly sort in reverse order.
Dot Net Perls
|© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, firstname.lastname@example.org.|