sujith karivelil
sujith karivelil

Reputation: 29036

Working Principle of Array.Sort()

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"}
  1. Why the numbers comes before alphabets?

  2. Is Array.Sort() performs sorting on the basics of ASCII code(ascii code of numbers are lower than letters)?

  3. How the Sort order is defined if the array consist of special characters and alpha-numeric?

Upvotes: 3

Views: 129

Answers (3)

Patrick Hofman
Patrick Hofman

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

user1196549
user1196549

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

SHM
SHM

Reputation: 1952

its logic is based on IComparable interface. and thus the default implementation which is used by sort method prefers numbers to alphabets.

second: its completely based on IComparable interface you can see docs in here

Upvotes: 0

Related Questions