2010年10月19日 星期二

雙向排序

'雙向排序
Public Class Form1
    Dim counter = 0
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '雙向排序 - 一次取得剩餘未處理部份的最大最小值
        Dim n() = {9, 8, 7, 6, 5, 4, 3, 2, 10, 1}
        Dim i1 = 0
        Dim i2 = n.Length - 1
        While i1 < i2
            Dim j1 = i1 + 1
            Dim j2 = i2 - 1
            While j1 <= n.Length - 1
                If n(i1) > n(j1) Then
                    change(n(i1), n(j1))
                End If
                If n(i2) < n(j2) Then
                    change(n(i2), n(j2))
                End If
                j1 = j1 + 1
                j2 = j2 - 1
            End While
            i1 = i1 + 1
            i2 = i2 - 1
        End While
        Dim str1 = ""
        For i = 0 To n.Length - 1
            str1 = str1 & n(i) & Space(3)
        Next
        str1 = str1 & vbNewLine & "交換:" & counter & "次 " & vbNewLine
        '單向排序
        counter = 0
        Dim n1() = {9, 8, 7, 6, 5, 4, 3, 2, 10, 1}
        Dim f1 = 0
        While f1 <= n.Length - 1 - 1
            Dim g1 = f1 + 1
            While g1 <= n.Length - 1
                If n1(f1) > n1(g1) Then
                    change(n1(f1), n1(g1))
                End If
                g1 = g1 + 1
            End While
            f1 = f1 + 1
        End While
        For i = 0 To n.Length - 1
            str1 = str1 & n1(i) & Space(3)
        Next
        str1 = str1 & vbNewLine & "交換:" & counter & "次 " & vbNewLine
        MsgBox(str1)
        End
    End Sub
    Sub change(ByRef x, ByRef y)
        Dim t = x
        x = y
        y = t
        counter = counter + 1
    End Sub
End Class

沒有留言: