Bubble sort Error (Compile Error: Type Mismtach)

E

Excel Monkey

I am having trouble using a Bubble Sort Sub. The issue is in the sub that
calls the sort sub. I keep getting a "Compile Error: Type Mismatch: array
or user defined type expected.". What am I doing wrong?

Sub Test()
Dim x As Variant

ReDim x(0 To 2)

x(0) = 1
x(1) = 10
x(2) = 3

BubbleSort (x)

Sub BubbleSort(MyArray() As Variant)
'Additional Sort code here
End Sub

Thanks

EM
 
J

Jim Thomlinson

x is single variable of type Variant. Your procedure Bubble sort expects an
array of variants. Just get rid of the brackets

Sub BubbleSort(MyArray As Variant)
 
B

Bernie Deitrick

Use

Sub BubbleSort(MyArray As Variant)

and not

Sub BubbleSort(MyArray() As Variant)

HTH,
Bernie
MS Excel MVP
 
E

Excel Monkey

Sorry, one last question. I have converted it to a function but I am not
getting the correct results. I am assuming that I have slipped a position in
the BubbleSort sub. I can figure out where the oversight is. Any ideas?

Sub Test()
Dim x As Variant

ReDim x(0 To 2)

x(0) = 10
x(1) = 7
x(2) = 4

x = BubbleSort(x)
Debug.Print x(0) & ", " & x(1) & ", " & x(2)
End Sub

Private Function BubbleSort(MyArray As Variant) As Variant
Dim First As Integer
Dim Last As Integer
Dim i As Integer
Dim j As Integer
Dim Temp As String
Dim List As String

First = LBound(MyArray)
Last = UBound(MyArray)
For i = First To Last
For j = i + 1 To Last - 1
If MyArray(i) > MyArray(j) Then
Temp = MyArray(j)
MyArray(j) = MyArray(i)
MyArray(i) = Temp
End If
Next j
Next i

BubbleSort = MyArray

End Function
 
H

HaSt2307

Excel Monkey,
If the data that you are sorting is a combination of Alpha and
Numeric of just numeric and you have 1, 2, ....,10,..20,..30 you will
get 1,10,2,20,3,30. I had the same thing. Change the line:

If MyArray(i) > MyArray(j) Then

TO

If Val(MyArray(i)) > Val(MyArray(j)) Then

HTH
Harry
 
B

Bernie Deitrick

Your biggest mistake was dimming Temp as a string, but you also don't need
to double increment through the indices.

Private Function BubbleSort(MyArray As Variant) As Variant
Dim First As Integer
Dim Last As Integer
Dim i As Integer
Dim j As Integer
Dim Temp As Variant
Dim Switched As Boolean

Switched = True
First = LBound(MyArray)
Last = UBound(MyArray)

While Switched
Switched = False
For i = First To Last - 1
j = i + 1
If MyArray(i) > MyArray(j) Then
Temp = MyArray(j)
MyArray(j) = MyArray(i)
MyArray(i) = Temp
Switched = True
End If
Next i
Wend

BubbleSort = MyArray

End Function


HTH,
Bernie
MS Excel MVP
 

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