Solved

How to sort numbers in a Listbox in desending order using an array and bubblesort

Posted on 2004-10-04
7
1,071 Views
Last Modified: 2013-12-26
I want to make a program that will sort the users inputed numbers in a desending order.  On my form I  have a listbox ,a texrbox and two cmdButtons.
The user enters a several numbers  (anywhere from a value of 1 to a million or so) example: 2; 25; 1,794; 4,009,546 etc.  They then click one of the cmdButtons and this number is added to the listbox and I am guessing to an array.  Once the user has entered all the numbers they need sorted., they click the other cmdButton and the  numbers in the listbox are sorted.  I am not familiar with sorting(bubble, quick) or arrays (how to populate them in real time)so any code on how to accomplish this would be greatly appreciated.  Also I guess I would need a third button  to clear listbox and the array (ReDim?) so the user could enter a new set of numbers to be sorted from least to greatest.
0
Comment
Question by:ucla11
  • 3
  • 2
  • 2
7 Comments
 
LVL 4

Accepted Solution

by:
cachedVB earned 250 total points
ID: 12220931
'This is the code to sort the listbox

Dim splt
splt = split(text1.text)
Dim num as integer
Dim i as integer
dim x as integer

for i = 0 to list1.listcount - 1
for x = i to list1.listcount - 1
if (val(list1.list(i)) > val(list1.list(x))) then
num = val(list1.list(i))
list1.list(i) = list1.list(x)
list1.list(x) = num
end if
next x
next i


To clear the listbox, just use list1.clear
0
 
LVL 4

Expert Comment

by:cachedVB
ID: 12221001
oops... the one above is in ascending order, to make it descending, make the line
if (val(list1.list(i)) < val(list1.list(x))) then
instead of
if (val(list1.list(i)) > val(list1.list(x))) then
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12221832
Private Sub Command1_Click()
    Dim values() As Long
    Dim tempValues As Variant
    Dim i As Integer
    Dim j As Integer
    Dim temp As Long
   
    ' build an array of your values
    tempValues = Split(Text1.Text, ";")
    ReDim values(UBound(tempValues))
    For i = LBound(tempValues) To UBound(tempValues)
        values(i) = CLng(tempValues(i))
    Next i
     
    ' bubble sort the values in descending order
    For i = (UBound(values) - 1) To 0 Step -1
        For j = 0 To i
            If values(j) < values(j + 1) Then
                temp = values(j)
                values(j) = values(j + 1)
                values(j + 1) = temp
            End If
        Next j
    Next i
     
    ' populate the listbox with the sorted values
    List1.Clear
    For i = LBound(values) To UBound(values)
        List1.AddItem values(i)
    Next i
End Sub
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 18

Expert Comment

by:JR2003
ID: 12221860
If you set the .Sorted property of the listbox to true at design time the list will be sorted alphabeticaly.
To make an alphabetic sort work on numberd you have to left pad the numbers with spaces as you add then to the list view. This is easy if you know the maximum length of your numbers.

Try the following code with the .Sorted property set to True and then false at design time.
e.g.

Private Sub Command1_Click()
    Dim i As Long
    Dim sNumber As String
    With List1
        For i = 1 To 10000
            sNumber = Format(Fix(Rnd() * i + 1), "#,##0")
            .AddItem Space(10 - Len(sNumber)) & sNumber
        Next i
    End With
End Sub

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12221898
But that will sort ascending not descending.  You would still have to create some kind of temp array, collection, or another listbox to hold the values temporarily so you can reverse the order of the items.

~IM
0
 
LVL 18

Expert Comment

by:JR2003
ID: 12223103
IM,
You're quite right. It's me not reading the question properly. I just have an aversion to ever using a bubble-sort due to its order n^2 time, though they are probably fine for 100 items or less as in this requirement.
JR

Just for interest here's a version that uses QuickSort to sort 32,000 items in the listbox and also a bubble-sort to sort the same items. It demonstrates why you should never use a bubble-sort when n gets large.

Option Explicit

Private Sub Command1_Click()

    'Populate the listbox with random numbers
    Dim i As Long
    Dim sNumber As String
    With List1
        .Clear
        For i = 1 To 32000
            sNumber = Format(Fix(Rnd() ^ 2 * 10000), "#,##0")
            .AddItem sNumber
        Next i
    End With

End Sub

Private Sub Command2_Click()

    'Quick-sort the listbox descending
    SortNumericListBox List1, False
   
End Sub

Private Sub Command3_Click()
    'Slow bubble-sort the listbox
    Dim i As Long
    Dim j As Long
    Dim Arr() As String
    Dim sTemp As String
    With List1
        ReDim Arr(.ListCount - 1) As String
        For i = 0 To .ListCount - 1
            Arr(i) = .List(i)
        Next i

        For i = LBound(Arr) To UBound(Arr)
            For j = 0 To i
                If CDbl(Arr(j)) < CDbl(Arr(j + 1)) Then
                    sTemp = Arr(j)
                    Arr(j) = Arr(j + 1)
                    Arr(j + 1) = sTemp
                End If
            Next j
        Next i
       
        .Clear
        For i = LBound(Arr) To UBound(Arr)
            .AddItem Arr(i)
        Next i
    End With
   
End Sub

Public Function SortNumericListBox(objListBox As ListBox, Optional Ascending As Boolean = True)
    'Sorts a listbox containing numeric values
    Dim MyArray() As String
    Dim i As Long
    With objListBox
        ReDim MyArray(0 To .ListCount - 1)
        For i = LBound(MyArray) To UBound(MyArray)
            MyArray(i) = .List(i)
        Next i
        QuickSortArray LBound(MyArray), UBound(MyArray), MyArray
        .Clear
        If Ascending Then
            For i = LBound(MyArray) To UBound(MyArray)
                .AddItem MyArray(i)
            Next i
        Else
            For i = UBound(MyArray) To LBound(MyArray) Step -1
                .AddItem MyArray(i)
            Next i
        End If
    End With
   
End Function


Private Function QuickSortArray(ByVal LowBound As Long, ByVal HighBound As Long, Array2Sort() As String)
   
    Dim intX As Long
    Dim intY As Long
    Dim MidBound As String
    Dim tmpElement As String
    Dim iCount As Long
    On Error GoTo PROC_ERR
    ' If there is data to sort
    If HighBound > LowBound Then
        ' Calculate the value of the middle array element
        MidBound = Array2Sort((HighBound + LowBound) \ 2)
        intX = LowBound
        intY = HighBound
        ' Split the array into halves
        Do While intX <= intY
            If CDbl(Array2Sort(intX)) >= CDbl(MidBound) And CDbl(Array2Sort(intY)) <= CDbl(MidBound) Then
                'Begin Swap
                tmpElement = Array2Sort(intX)
                Array2Sort(intX) = Array2Sort(intY)
                Array2Sort(intY) = tmpElement
                'End Swap
                intX = intX + 1
                intY = intY - 1
            Else
                If CDbl(Array2Sort(intX)) < CDbl(MidBound) Then
                    intX = intX + 1
                End If
                If CDbl(Array2Sort(intY)) > CDbl(MidBound) Then
                    intY = intY - 1
                End If
            End If
        Loop
        'Sort the lower half of the array
        QuickSortArray LowBound, intY, Array2Sort
        'Sort the upper half of the array
        QuickSortArray intX, HighBound, Array2Sort
    End If

PROC_EXIT:

    Exit Function
   
PROC_ERR:

    Beep
    MsgBox "Error: " & Err.Number & ". " & Err.Description, vbExclamation
    Resume PROC_EXIT

End Function
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12223354
I quite agree.  Only use Bubble Sort for small data sets.

~IM
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now