sort function - from ascending to descending

  • Thread starter Thread starter jimmyp
  • Start date Start date
J

jimmyp

hi

i have this bubblesort sub -


Code:
--------------------

Sub BubbleSort(List() As Integer)

Dim First As Integer, Last As Integer
Dim i As Integer, j As Integer
Dim Temp As Integer

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


--------------------


but at the moment it sorts all the elements in ascending order, and i
need it biggest element first ie. descending...

any idea how i change it, i guess it would be simple but i suppose it
may need completely rewriting :confused:

thanks


jimmyp
 
Hi
try changing the test
If List(i) > List(j)
to
If List(i) < List(j)

(untested)
Paul
 
i tried that - it almost works :) but misses of the largest element, ie
the one that should be at the start...the rest are all in descending
order though :confused:
 
It should work as demonstrated here:

Sub BubbleDown()
Dim First As Integer, Last As Integer
Dim i As Integer, j As Integer
Dim Temp As Integer
List = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
First = LBound(List)
Last = UBound(List)
For i = First To Last - 1
For j = i + 1 To Last
If List(i) < List(j) Then
Temp = List(j)
List(j) = List(i)
List(i) = Temp
End If
Next j
Next i
For i = First To Last
Debug.Print i, List(i)
Next
End Sub
 
tom essentially thats the same as what i posted except you have 'List =
Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)' whereas i pass in my array from
another sub. Thing is its still missing the first element, but if i
change back to > then it displays all the elements, just in the wrong
order... its odd the only thing i change is the <.
 
that is correct - I was showing you that it does work to reverse the order of
an array.

The only problem I can think of is that you recalcitrant value is being
stored as a string rather than a number. As long as the string is never
moved, you won't get an error. If your code does try to move it, then it
will raise an error since temp is Dim'd as Integer.
 
Back
Top