Advertisement
Guest User

Untitled

a guest
May 26th, 2015
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Public Module quicksort
  2.     Public Sub quicksort(ByRef A As List(Of iQuicksortable))
  3.         qsort(A, 0, A.Count - 1)
  4.     End Sub
  5.  
  6.     Private Sub qsort(ByRef A As List(Of iQuicksortable), lo As Integer, hi As Integer)
  7.         If lo < hi Then
  8.             Dim p As Integer = partition(A, lo, hi)     'run partition and get index of pivot
  9.            qsort(A, lo, p - 1)         '-1 because pivot was at p and can be excluded
  10.            qsort(A, p + 1, hi)         '+1 because pivot was at p and can be excluded
  11.        End If
  12.     End Sub
  13.  
  14.     Private Function partition(ByRef A As List(Of iQuicksortable), lo As Integer, hi As Integer) As Integer
  15.         'lo is the index of the leftmost element
  16.        'hi is the (inclusive) index of the rightmost element
  17.        Dim pivotIndex As Integer = choosePivot(A, lo, hi)
  18.         Dim pivotValue As Integer = A(pivotIndex).qsValue
  19.  
  20.  
  21.         'put pivot at A(hi)
  22.        swap(A, pivotIndex, hi)
  23.         Dim storeIndex As Integer = lo
  24.  
  25.  
  26.         'compare each value between A(lo) and A(hi) with pivot
  27.        For i = lo To hi - 1                    '-1 because pivot is at A(hi)
  28.            If A(i).qsValue <= pivotValue Then
  29.                 swap(A, i, storeIndex)
  30.                 storeIndex += 1
  31.             End If
  32.         Next
  33.  
  34.  
  35.         'move pivot to final place
  36.        swap(A, storeIndex, hi)
  37.  
  38.  
  39.         'return index of pivot's final place
  40.        Return storeIndex
  41.     End Function
  42.  
  43.     Private Sub swap(ByRef A As List(Of iQuicksortable), p1 As Integer, p2 As Integer)
  44.         If p1 = p2 Then Exit Sub
  45.  
  46.         Dim tempValue As iQuicksortable = A(p1)
  47.         A(p1) = A(p2)
  48.         A(p2) = tempValue
  49.     End Sub
  50.  
  51.     Private Function choosePivot(ByRef A, p1, p2) As Integer
  52.         Return CInt(Math.Abs(p2 - p1) / 2)
  53.     End Function
  54. End Module
  55.  
  56. Public Interface iQuicksortable
  57.     Property qsValue As Integer
  58. End Interface
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement