r/visualbasic • u/PostalElf VB.Net Intermediate • May 26 '15
Sort [VB.NET] Failed implementation of quicksort
Hey guys, can someone tell me why my quicksort doesn't work? It's an implementation of the pseudocode found at wiki and, as far as I can figure out, everything seems to be correct. I even followed it on paper and, as far as I can see, the logic is right: but the results I end up getting are far from sorted.
Appreciate any help!
6
Upvotes
2
u/Bonejob VB Guru May 27 '15
Man this brought back some memories, I did this one for school 30 years ago >.< in C
Here is a quick implementation in VB console app as always :) Check how the pivot is handled by binary splitting right at the top using an iComparable.
Public Sub Main(args As String())
' Implementation of
' http://www.wikiwand.com/en/Quicksort
' Create array to sort
Dim sortArray As String() = {"t", "x", "a", "r", "s", "w", "k", "g", "o"}
For x = 0 To sortArray.Length - 1
Console.Write(sortArray(x) + " ")
Next
Console.WriteLine()
Quicksort(sortArray, 0, sortArray.Length - 1)
' output array
For i As Integer = 0 To sortArray.Length - 1
Console.Write(sortArray(i) + " ")
Next
Console.WriteLine()
Console.ReadKey()
End Sub
Public Sub Quicksort(atom As IComparable(), left As Integer, right As Integer)
Dim leftInt As Integer = left, rightInt As Integer = right
Dim pivot As IComparable = atom((left + right) / 2)
While leftInt <= rightInt
While atom(leftInt).CompareTo(pivot) < 0
leftInt += 1
End While
While atom(rightInt).CompareTo(pivot) > 0
rightInt -= 1
End While
If leftInt <= rightInt Then
Dim tmp As IComparable = atom(leftInt)
atom(leftInt) = atom(rightInt)
atom(rightInt) = tmp
leftInt += 1
rightInt -= 1
End If
End While
If left < rightInt Then
Quicksort(atom, left, rightInt)
End If
If leftInt < right Then
Quicksort(atom, leftInt, right)
End If
End Sub
1
u/PostalElf VB.Net Intermediate May 26 '15 edited May 26 '15
OK I think I figured out my problem, it's my implementation of choosePivot(). I'll edit this post once I fix it.
EDIT: ok it's definitely choosePivot. I've since replaced with a random index between lo and hi and it works! However, I'll still appreciate if anyone has any ideas on how I can take the median value of first, middle and last elements to calculate the index (aka Sedgewick's recommendation).