|
-
Mar 8th, 2000, 03:10 AM
#1
Thread Starter
New Member
VB guru's, how do i sort an array of names using quicksort in VB.
-
Mar 8th, 2000, 03:24 AM
#2
I found this routine somewhere on the web, but I forgot where.
It works great 
Code:
Public Sub Quicksort(List() As String, Min As Integer, Max As Integer)
Dim med_value As String
Dim hi As Integer
Dim lo As Integer
Dim i As Integer
' If the list has no more than 1 element, it's sorted.
If Min >= Max Then Exit Sub
' Pick a dividing item.
i = Int((Max - Min + 1) * Rnd + Min)
med_value = List(i)
' Swap it to the front so we can find it easily.
List(i) = List(Min)
' Move the items smaller than this into the left
' half of the list. Move the others into the right.
lo = Min
hi = Max
Do
' Look down from hi for a value < med_value.
Do While List(hi) >= med_value
hi = hi - 1
If hi <= lo Then Exit Do
Loop
If hi <= lo Then
List(lo) = med_value
Exit Do
End If
' Swap the lo and hi values.
List(lo) = List(hi)
' Look up from lo for a value >= med_value.
lo = lo + 1
Do While List(lo) < med_value
lo = lo + 1
If lo >= hi Then Exit Do
Loop
If lo >= hi Then
lo = hi
List(hi) = med_value
Exit Do
End If
' Swap the lo and hi values.
List(hi) = List(lo)
Loop
' Sort the two sublists
Quicksort List(), Min, lo - 1
Quicksort List(), lo + 1, Max
End Sub
You can call this routine like:
Code:
Call Quicksort(MyList, LBound(MyList), UBound(MyList))
-
Mar 8th, 2000, 03:39 AM
#3
Frenzied Member
Here's another
Actually, it looks very similar to the one above. Works great, too!
Code:
Private Sub QuickSort(SortList As Variant, ByVal First As Integer, _
ByVal Last As Integer)
'Purpose: This function sorts a list from lowest to highest (0 - 9 for
' numeric arrays, A - z for string arrays). This is a recursive
' function, meaning that it calls itself in order to solve
' the problem.
'
'Arguments: SortList: An array of items to be sorted (Variant)
' First: The index of the first item in the array (Integer)
' Last: The index of the last item in the array (Integer)
'
'Note: There is no "return value". However, the argument list is
' returned with it's elements sorted. If you want to retain
' your original list, pass this function a copy of the list.
'
Dim Low As Integer, _
High As Integer, _
Temp As Variant, _
TestElement As Variant
Low = First
High = Last
TestElement = SortList((First + Last) / 2)
Do
Do While SortList(Low) < TestElement
Low = Low + 1
Loop
Do While SortList(High) > TestElement
High = High - 1
Loop
If (Low <= High) Then
Temp = SortList(Low)
SortList(Low) = SortList(High)
SortList(High) = Temp
Low = Low + 1
High = High - 1
End If
Loop While (Low <= High)
If (First < High) Then
Call QuickSort(SortList, First, High)
End If
If (Low < Last) Then
Call QuickSort(SortList, Low, Last)
End If
End Sub
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|