How To Change QuickSort Ascending To Descending
-
Friday, July 24, 2009 5:07 PM
I am using a quicksort algorithm for listing information in ascending order. How would I change it to list the items in descending order. The site I was at said to switch the comparison operators but that doesn't seem to work. Here is the code for what I have :
'This function sorts the particular list box using the Quick Sort algorithm [ASCENDING] Private Sub Sort_List_Boxes_Ascending(ByRef vArray() As String, ByVal inLow As Integer, ByVal inHi As Integer) Dim pivot As Object Dim tmpSwap As Object Dim tmpLow As Long Dim tmpHi As Long tmpLow = inLow tmpHi = inHi pivot = vArray((inLow + inHi) \ 2) While (tmpLow <= tmpHi) While (vArray(tmpLow) < pivot And tmpLow < inHi) tmpLow = tmpLow + 1 End While While (pivot < vArray(tmpHi) And tmpHi > inLow) tmpHi = tmpHi - 1 End While If (tmpLow <= tmpHi) Then tmpSwap = vArray(tmpLow) vArray(tmpLow) = vArray(tmpHi) vArray(tmpHi) = tmpSwap tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If End While If (inLow < tmpHi) Then Sort_List_Boxes_Ascending(vArray, inLow, tmpHi) If (tmpLow < inHi) Then Sort_List_Boxes_Ascending(vArray, tmpLow, inHi) End SubThanks!
All Replies
-
Friday, July 24, 2009 5:50 PM
Well, first thing - Are you aware that Array.Sort uses the QuickSort to do it's sorting? So, there is no real reason to implement QuickSort at all for your particular operation.
Now assuming your in VB2008, you can quite simply do as you ask:
Option Explicit On Option Strict On Module Module1 Sub Main() Dim a() As String = {"D", "A", "C", "B"} ' assending Array.Sort(a) PrintArray(a) 'descending Array.Sort(a, Function(x, y) x.CompareTo(y) * -1) PrintArray(a) End Sub Private Sub PrintArray(ByVal a() As String) Console.WriteLine(String.Join(", ", a)) End Sub End ModuleHTH
Tom Shelton- Marked As Answer by NuNn DaDdY Friday, July 24, 2009 8:05 PM
- Unmarked As Answer by NuNn DaDdY Friday, July 24, 2009 8:06 PM
- Marked As Answer by NuNn DaDdY Friday, July 24, 2009 8:07 PM
-
Friday, July 24, 2009 7:50 PMI am having issues with your solution as I keep receiving "Item cannot be null when I try adding my array back to the listbox" .
Could you/someone direct me on reversing the sort order of the quicksort
*CORRECTION* You were right Tom, my apologies. An error in my code on my part. Thank you very much!
But if someone could still provide the descending info that would be appreciated- Edited by NuNn DaDdY Friday, July 24, 2009 8:07 PM

