Sorting a two Dimensional Array

nick447923

Member
Joined
Nov 10, 2009
Messages
14
Programming Experience
Beginner
I am writing an auto insurance application. I need to sort a three dimensional array in descending order based on an integer value in third field in the array.
The CalcPremium function returns an integer value.

Dim CarDriverArray(3, 3)
CarDriverArray(0, 0) = "D1"
CarDriverArray(0, 1) = "C1"
CarDriverArray(0, 2) = CalcPremium()
CarDriverArray(1, 0) = "D2"
CarDriverArray(1, 1) = "C1"
CarDriverArray(1, 2) = CalcPremium()
CarDriverArray(2, 0) = "D3"
CarDriverArray(2,1) = "C1"
CarDriverArray(2,2) = CalcPremium()

I need to sort the CalcPremium element in the array in descending order.
I tried using the sort function but it states it requires a one dimensional array. How would this be accomplished?
 
While you can do it with IComparer wouldn't you be better off putting this information in a DataTable?

VB.NET:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim obj1() As Object = New Object() {"D1", "C1", 2}
        Dim obj2() As Object = New Object() {"D2", "C1", 0}
        Dim obj3() As Object = New Object() {"D3", "C1", 1}

        Dim CarDriverArray()() As Object = {obj1, obj2, obj3}

        Dim comp As New JagComparer
        Array.Sort(CarDriverArray, comp)

    End Sub
End Class

Public Class JagComparer
    Implements IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        'x & y are Object()
        Dim arr1() As Object = DirectCast(x, Object)
        Dim arr2() As Object = DirectCast(y, Object)
        Return -CInt(arr1(2)).CompareTo(CInt(arr2(2)))
    End Function
End Class

Oops. Didn't see the descending requirement on the original post. Changed the sign of the Compare functions return.
 
Last edited:
Save all the values to a one-dimensional array using the length of the 3D array, and then sort it:

VB.NET:
                Dim N As Integer = ArrayDim.Length
		Dim x As Integer = 0
		Dim OneArray(N - 1) As String
		For Each valu As String In ArrayDim
			OneArray(x) = valu
			x += 1
		Next valu
		Array.Sort(OneArray)
                Array.Reverse(OneArray)
		For Each valu As String In OneArray
			'display the values
		Next valu

Note: Your original post lists a two-dimensional array, not 3D. The above code will work with either dimension. To display in descending order, first you must use the Sort method, and then the Reverse method.
 
Last edited:
I just realized you only want to extract the integer values. In that case, you can add the following code to the end of my previous post:

VB.NET:
Dim num As Integer
For i As Integer = 0 To N - 1
	If Integer.TryParse(OneArray(i), num) <> 0 Then
		'display the value
	End If
Next i
 

Latest posts

Back
Top