Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Dear All,

I have two arrays (array1 and array2)with double type data. I want to sort array1 to ascending order, and array2 with corresponding to the array1 indexes. Is this possible? Example below,

Array1(0) = 2.30
Array1(1) = 4.20
Array1(2) = 1.90
Array1(3) = 0.20
Array1(4) = 0.88

Array2(0) = 0.19
Array2(1) = 0.002
Array2(2) = 0.20
Array2(3) = 0.45
Array2(4) = 1.8

Resulted arrays should be as,

Result1(0) = 4.20
Result1(1) = 2.30
Result1(2) = 1.90
Result1(3) = 0.88
Result1(4) = 0.20

Result2(0) = 0.002
Result2(1) = 0.19
Result2(2) = 0.20
Result2(3) = 1.8
Result2(4) = 0.45

Can anybody help me to get these results arrays? I use VB.NET 2010.
Thanks
Posted
Updated 25-Apr-12 15:22pm
v2
Comments
VJ Reddy 26-Apr-12 4:19am    
Thank you for accepting the solution.

1 solution

The Array.Sort(Of TKey, TValue) Method (TKey(), TValue(), IComparer(Of TKey)) explained here http://msdn.microsoft.com/en-us/library/x8kwfbye.aspx[^] can be used for this purpose. In the present case, as the sorting is to be done in Descending order IComparer is required, which is explained here
http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx#Y700[^]
is required

VB
Private Sub Main()
    Dim Array1(4) As  Double
    Dim Array2(4) As Double

    Array1(0) = 2.3
    Array1(1) = 4.2
    Array1(2) = 1.9
    Array1(3) = 0.2
    Array1(4) = 0.88

    Array2(0) = 0.19
    Array2(1) = 0.002
    Array2(2) = 0.2
    Array2(3) = 0.45
    Array2(4) = 1.8

    Array.Sort(Of Double, Double)(Array1, Array2, New ItemComparer())

End Sub

'ItemComparer for sorting in the Descending order
Public Class ItemComparer
    Implements IComparer(Of Double)

    Public Function Compare(x As Double, y As Double) As Integer _
        Implements IComparer(Of Double).Compare

        Return y.CompareTo(x)
    End Function
End Class
 
Share this answer
 
v2
Comments
Member 8312096 26-Apr-12 4:21am    
Dear VJ Reddy,
Great!!!!! its working fine. Thanks a lot. This is a small snippet, but it does a big task for me. Thanks again.
VJ Reddy 26-Apr-12 4:23am    
You're welcome and
thank you for the response.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900