主程式:
Module ModuleW5000 Private MySort As ClassSort = New ClassSort() Sub Main() Dim MySort As ClassSort = New ClassSort() MySort.LoadData({3, 5, 7, 1, 2, 15, 9, 10, -3, 8}) ' 由小到大 MySort.Sort(False) MySort.Print() Console.ReadKey() End Sub End Module
ClassSort:
Public Class ClassSort Private SourceData As ArrayList = Nothing Private MaxValue As Double = -1 Private MaxValuePosition As Integer = -1 ' 建構子 Public Sub New() Me.SourceData = New ArrayList() End Sub ' 載入資料至陣列 Public Sub LoadData(Data() As Double) Me.SourceData.Clear() For i = 0 To Data.Count - 1 Me.SourceData.Add(Data(i)) Next End Sub ' 交換兩位置之值 Public Sub SwapValues(X_Position As Integer, Y_Position As Integer) Dim TempValue As Double = 0 ' 兩位置相同 If X_Position = Y_Position Then Return End If ' X 位置超出範圍 If Not (X_Position < Me.SourceData.Count And X_Position >= 0) Then Return End If ' Y 位置超出範圍 If Not (Y_Position < Me.SourceData.Count And Y_Position >= 0) Then Return End If ' 交換 TempValue = Me.SourceData(X_Position) Me.SourceData(X_Position) = Me.SourceData(Y_Position) Me.SourceData(Y_Position) = TempValue End Sub Public Sub Sort(Descendant As Boolean) ' 探索下一個至最末個元素 For i = 0 To Me.SourceData.Count - 2 ' 假定第一個元素為最大值 Me.MaxValuePosition = i Me.MaxValue = Me.SourceData(Me.MaxValuePosition) ' 找下一個至最末個元素範圍內最大值 Me.FindMaxValuePosition(i + 1, Me.SourceData.Count - 1, Descendant) ' 對調 [假定最大值位置] 與 [所尋找之最大值位置] 中值 Me.SwapValues(i, Me.MaxValuePosition) Next End Sub Public Sub FindMaxValuePosition(Start_Position As Integer, End_Position As Integer, Descendant As Boolean) Dim CompareValue As Boolean ' 探索每一個至最末個元素 For i = Start_Position To End_Position If Descendant Then CompareValue = Me.MaxValue < Me.SourceData(i) Else CompareValue = Me.MaxValue > Me.SourceData(i) End If ' 若當前值比前一個最大值還大 If CompareValue Then Me.MaxValuePosition = i Me.MaxValue = Me.SourceData(Me.MaxValuePosition) End If Next End Sub Public Sub Print() For i = 0 To Me.SourceData.Count - 1 Console.Write(Me.SourceData(i)) Console.Write(vbTab) Next Console.Write(vbCrLf) End Sub End Class