Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4.0 internal implementation of sort

Tags:

.net

algorithm

I've found out that inside the Array.Sort,

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool TrySZSort(Array keys, Array items, int left, int right);

gets called. Any ideas how this is implemented?

like image 669
Roman Dzhabarov Avatar asked Aug 14 '12 00:08

Roman Dzhabarov


2 Answers

You can get a fairly reliable copy of the CLR source code from the SSCLI20 source distribution. It was published in 2005 and, at the time, was a pretty accurate copy of CLR version 2. Never found an obvious discrepancy.

That's moved on since then, already 7 years ago and a rather major CLR version update since. But TrySZSort() is still around, those low-level implementations are highly self-preserving. You'll find it declared in clr/src/vm/ecall.cpp and mapped to ArrayHelper::TrySZSort(), a C++ method declared in clr/src/vm/arrayhelpers.cpp

It is otherwise very boring, it just calls a template class method named ArrayHelpers<T>.QuickSort(), specialized by array element type for value type elements.

Which is just the way Tony Hoare wrote it up 52 years ago. Albeit not in C++ ;)

You'll find the reason this code is written in C++ and not in C# in this answer.

like image 70
Hans Passant Avatar answered Oct 01 '22 17:10

Hans Passant


Any ideas how this is implemented?

That method is implemented in native code, internal within the CLR itself. There are many methods like this on the very core, low level types. For example, quite a few of the methods on System.String are flagged InternalCall and implemented in the common language runtime itself.

like image 41
Reed Copsey Avatar answered Oct 01 '22 15:10

Reed Copsey