Sort listbox with string items ascending and descending
How would one code a button so upon cliking it items in listbox would sort either ascending or descending (depends on the button clicked). It mustn't be done with built-i开发者_运维技巧n Sort()
but with a for
loop for example. Tried to pseudo-code the solution to the problem, went as far as "store each listbox item in an array with a for loop".
i will provide you the solution for this but for sorting numbers, you only have to change the comparison logic in order to determine which string is greater than the other one.
step-1 : copy the items from the listbox to an array ar. step-2: use quick sort:
Private quickArr() As Integer
Public Sub QuickSort(ByVal arr() As Integer)
quickArr = arr
DoQuickSort(0, arr.Length - 1)
End Sub
Private Sub DoQuickSort(ByVal low As Integer, ByVal high As Integer)
Dim i As Integer = low
Dim j As Integer = high
Dim pivot As Integer = Math.Ceiling(quickArr(((low + high) / 2))) 'pivot is the middle element(ceiling)
mMoves += 1
While i <= j
While quickArr(i) < pivot
i += 1
End While
While quickArr(j) > pivot
j -= 1
End While
If i <= j Then
Dim t As Integer = quickArr(i)
quickArr(i) = quickArr(j)
quickArr(j) = t
i += 1
j -= 1
mMoves += 2
End If
End While
If low < j Then
DoQuickSort(low, j)
End If
If i < high Then
DoQuickSort(i, high)
End If
End Sub
3-copy the resuly array back to the listbox
精彩评论