Sort an array

J

Julie

I have an array with numbers. I want the numbers sorted.

Is there a built-in function that can do that?

Otherwise I'll write some code to do it. My array has up
to 100 numbers.
 
B

Bas Cost Budde

Julie said:
I have an array with numbers. I want the numbers sorted.

Is there a built-in function that can do that?

Otherwise I'll write some code to do it. My array has up
to 100 numbers.

In JavaScript, yes. In VBA, no.

If you have to sort just 100 items, bubblesort will not hamper your
performance too severely. You could implement another sorting algorithm
of course
 
A

Alex Dybenko

Hi Julie,
here some code i am using:

Sub BubbleSort(pstrItem() As String)

Dim intDone As Integer, intRow As Integer, intLastItem As Integer
intLastItem = UBound(pstrItem)
Do
intDone = True
For intRow = 1 To intLastItem - 1
If pstrItem(intRow) > pstrItem(intRow + 1) Then
SwapStr pstrItem(), intRow, intRow + 1
intDone = False
End If
Next
Loop Until intDone
End Sub
Sub SwapStr(pstrItem() As String, ByVal pintRow1 As Integer, ByVal pintRow2
As Integer)

' Swaps two elements of pstrItem()
'
' Called from all sort routines except strInsertSort
'
Dim strTemp As String
'
strTemp = pstrItem(pintRow1)
pstrItem(pintRow1) = pstrItem(pintRow2)
pstrItem(pintRow2) = strTemp

End Sub
 
B

Bas Cost Budde

Alex said:
Hi Julie,
here some code i am using:

Sub BubbleSort(pstrItem() As String)

Dim intDone As Integer, intRow As Integer, intLastItem As Integer
intLastItem = UBound(pstrItem)
Do
intDone = True
For intRow = 1 To intLastItem - 1
If pstrItem(intRow) > pstrItem(intRow + 1) Then
SwapStr pstrItem(), intRow, intRow + 1
intDone = False
End If
Next
Loop Until intDone
End Sub

You don't have to walk to intLastItem every pass: after the first loop,
you are sure that the item with the highest value is in the last position.

If you add
intLastItem = intLastItem - 1
just before the Loop Until, you will have a noticeable increase in
efficiency.
 
A

Alex Dybenko

hi,
Thanks, probably you right, i use this for long time, performance was ok for
me, so i didnt think to improve it
 
B

Bas Cost Budde

Alex said:
hi,
Thanks, probably you right, i use this for long time, performance was ok for
me, so i didnt think to improve it
It's hard to note the difference for 100 items. For 1000 it becomes
clearly noticeable (but using another algorithm saves much more time)
 

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