0

I am using Array.Sort() with the parameters shown in the code. I'm unable to get the required order for the following array

jONeS
jones
joNes
jones
aDaMs
adams
adaMS
ADAMs

The program shown prints the following

adams
aDaMs
adaMS
ADAMs
jONeS
jones
joNes
jones

Where as according to me the following order should be printed

aDaMs
adams
adaMS
ADAMs
jONeS
jones
joNes
jones

Note the first two elements displayed wrongly. Where am I going wrong?

int N = Convert.ToInt32(Console.ReadLine());
string[] arr=new string[N];
for (int i = 0; i < N; ++i)
    arr[i] = Console.ReadLine();
Array.Sort(arr, StringComparer.Create(new CultureInfo("en-US"),true));
Console.WriteLine();
for (int i = 0; i < N; ++i)
    Console.WriteLine(arr[i]);
Jeroen Mostert
  • 27,176
  • 2
  • 52
  • 85
  • 2
    Am I the only one who look at `ADAMs` and ask , how come it is in different color ? – Royi Namir Oct 07 '15 at 20:53
  • 2
    Am I correct in assuming that you want the order of your elements preserved when they compare equal? If so, `Array.Sort()` uses Quicksort, which is not a stable sort. As long as two elements compare equalish (and this is the case for all the Adamses and Joneses) *any* output where the Adamses come before the Joneses is correct. If you additionally wish to preserve the original order of the elements, you need a stable sort algorithm like Mergesort. – Jeroen Mostert Oct 07 '15 at 21:25

1 Answers1

3

As Jeroen Mostert said Array.Sort is unstable (reference) however OrderBy in LINQ is stable (reference) you could use that.

So replace

Array.Sort(arr, StringComparer.Create(new CultureInfo("en-US"),true));

with

arr = arr.OrderBy(name=>name, StringComparer.Create(new CultureInfo("en-US"),true)).ToArray();
Sign
  • 1,919
  • 18
  • 33
  • Of course `OrderBy`doesn't actually sort the array but rather creates a new one. But that might very well work for the op. – Magnus Oct 07 '15 at 21:58