Sort an array

  • Thread starter Thread starter Julie
  • Start date Start date
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.
 
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
 
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
 
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.
 
hi,
Thanks, probably you right, i use this for long time, performance was ok for
me, so i didnt think to improve it
 
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)
 
Back
Top