Merge sort problem (VB.net)

Started by
1 comment, last by ConorH 14 years, 7 months ago
Im having trouble implementing a Mergesort routine on a List in VB.net. It sorts the first time, but subsequent sorts reduce the list size. This might just be because Im translating pseudocode. Im more suited to C++ so could someone give this a quick glance and tell me where Im going wrong? The site im using for reference http://www.codecodex.com/wiki/Merge_sort#Pseudocode Chars

Public Function mergesort(ByVal m As List(Of Customer))
        Dim left As New List(Of Customer)
        Dim right As New List(Of Customer)
        Dim middle As Integer
        Dim aftermiddle As Integer
        Dim result As New List(Of Customer)


        If m.Count < 2 Then

            'Already sorted
            Return m

        Else

            'Sort here
            middle = (m.Count - 1) / 2
            aftermiddle = middle + 1
            For t = 0 To middle
                left.Add(m(t))
            Next t

            For y = aftermiddle To m.Count - 1
                right.Add(m(y))
            Next y

            left = mergesort(left)
            right = mergesort(right)
            result = merge(left, right)
            Return result

        End If

    End Function

    Function merge(ByVal l As List(Of Customer), ByVal r As List(Of Customer))
        Dim result As New List(Of Customer)

        While l.Count > 0 And r.Count > 0
            If l(0).Name <= r(0).Name Then
                result.Add(l(0))
                l.RemoveAt(0)
            Else
                result.Add(r(0))
                r.RemoveAt(0)
            End If
            
        End While
        If l.Count > 0 Then
            result.Add(l(0))
            l.RemoveAt(0)
        End If

        If r.Count > 0 Then
            result.Add(r(0))
            r.RemoveAt(0)
        End If

        Return result
    End Function

Advertisement
The one gotcha that might be getting you is vb's rounding - Most languages truncate values, vb does banker's rounding - so when you do middle = (m.Count - 1) / 2
, you might want to try doing math.truncate(middle = (m.Count - 1) / 2) and see if that fixes your issue.
I did wonder how VB handled that, but it didnt help. Any other ideas?

Cheers

This topic is closed to new replies.

Advertisement