A
AMercer
The class below exhibits an inefficiency in Array.Sort, namely comparing an
array element to itself several times during Array.Sort's execution. To
recreate the problem, paste the code below in a test program, instantiate
TestArraySort, and call TestSort.
I have never seen Array.Sort fail, so all I am claiming is an inefficiency.
I stumbled on this while experimenting with generic interfaces. I suggest
this be forwarded to MS for review.
-------------------
Public Class TestArraySort ' expose an inefficiency in Array.Sort
' Array.Sort performs unnecessary comparisons by comparing an element to
itself.
Implements Collections.Generic.IComparer(Of Integer) ' for Array.Sort with
generic comparer
Public a() As Integer ' the array being sorted, visible from a break in
Compare()
Public Function Compare(ByVal x As Integer, ByVal y As Integer) As Integer _
Implements System.Collections.Generic.IComparer(Of Integer).Compare
Debug.Assert(x <> y) ' fail if keys are equal
Return x - y
End Function
Public Sub TestSort() ' Call this to cause an assertion failure in Compare
Randomize()
Dim n As Integer = 5
ReDim a(n)
For i As Integer = 1 To n
a(i) = CInt(Rnd(1) * 100) ' random data
a(i) = a(i) * 100 + i ' guarantee keys are unequal
Next
Array.Sort(a, 1, n, Me) ' sort using Compare() above
End Sub
End Class
array element to itself several times during Array.Sort's execution. To
recreate the problem, paste the code below in a test program, instantiate
TestArraySort, and call TestSort.
I have never seen Array.Sort fail, so all I am claiming is an inefficiency.
I stumbled on this while experimenting with generic interfaces. I suggest
this be forwarded to MS for review.
-------------------
Public Class TestArraySort ' expose an inefficiency in Array.Sort
' Array.Sort performs unnecessary comparisons by comparing an element to
itself.
Implements Collections.Generic.IComparer(Of Integer) ' for Array.Sort with
generic comparer
Public a() As Integer ' the array being sorted, visible from a break in
Compare()
Public Function Compare(ByVal x As Integer, ByVal y As Integer) As Integer _
Implements System.Collections.Generic.IComparer(Of Integer).Compare
Debug.Assert(x <> y) ' fail if keys are equal
Return x - y
End Function
Public Sub TestSort() ' Call this to cause an assertion failure in Compare
Randomize()
Dim n As Integer = 5
ReDim a(n)
For i As Integer = 1 To n
a(i) = CInt(Rnd(1) * 100) ' random data
a(i) = a(i) * 100 + i ' guarantee keys are unequal
Next
Array.Sort(a, 1, n, Me) ' sort using Compare() above
End Sub
End Class