sort 2D array

G

Greg

Hi,

Here is a bubble sort for an array in ascending order I've taken from J-Walk
book. Could some one help my modify it to sort a 2D array based on 1st
row(column)?

I only need an ascending order, and I think if it only sorts horizontal
array I'd be fine as well.

Your help is very much appreciated.

VBA:

Sub BubbleSortNumbers(iArray As Variant)
'Sorts the iArray in ascending order
Dim First As Single, Last As Single
Dim lTemp As Single
Dim j As Integer, i As Integer

First = LBound(iArray)
Last = UBound(iArray)


For i = First To Last - 1
For j = i + 1 To Last
If iArray(i) > iArray(j) Then
lTemp = iArray(j)
iArray(j) = iArray(i)
iArray(i) = lTemp
End If
Debug.Print i, iArray(i)
Debug.Print j, iArray(j)
Next j
Next i


End Sub
 
T

Toppers

Greg,
Try this:

Sub BubbleSort2D(iArray As Variant)
'Sorts the iArray in ascending order
Dim First As Integer, Last As Integer
Dim lTemp As Variant
Dim j As Integer, i As Integer, k As Integer

First = LBound(iArray, 1)
Last = UBound(iArray, 1)
FirstCol = LBound(iArray, 2)
Lastcol = UBound(iArray, 2)
For i = First To Last - 1
For j = i + 1 To Last
If iArray(i, 1) > iArray(j, 1) Then
For k = FirstCol To Lastcol
lTemp = iArray(j, k)
iArray(j, k) = iArray(i, k)
iArray(i, k) = lTemp
Next k
End If
Next j
Next i


End Sub

Sub test()
Dim arr() As Variant
arr = Range("a1:D20")
BubbleSort2D arr
Range("a1:D20") = arr
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top