Reputation: 29036
I am having an input array defined as follows:
string[] inputArray = { "a", "s", "d", "f", "g", "2", "3", "34", "4", "4", "y", "a", "f", "8", "h", "m" };
When i perform Sorting over this array i am getting the output as:
{"2","3","34","4","4","8","a","a","d","f","f","g","h","m","s","y"}
Why the numbers comes before alphabets?
Is Array.Sort()
performs sorting on the basics of ASCII code(ascii code of numbers are lower than letters)?
Upvotes: 3
Views: 129
Reputation: 157098
Because Array.Sort
uses the default comparer in order to sort. And that comparer will compare both strings based on the current culture (note that the comparer has a fail-over mechanism when both sides are strings). That will usually compare them based on their character code, and then numbers come before letters.
Upvotes: 3
Reputation:
Strings are compared in the so-called lexicographical ordering, meaning that you compare the two first characters, and in case of equality compare the next two and so on. If one of the strings ends before the other, it comes first.
Two characters are indeed compared on their numerical value, usually ASCII. In the ASCII table, control characters (non printable) come first, then digits, uppercase letters, lowercase letters, and special characters in between these groups.
Upvotes: 1