2009年6月15日 星期一

副程式例

'副程式例
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '氣泡排序 
        Dim a() = {95, 90, 98, 92, 96} 
        sortIt(a) 
        printIt(a)

        Dim b() = {95, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87} 
        sortIt(b) 
        printIt(b)

        Dim c() = {95, 90} 
        sortIt(c) 
        printIt(c)

        Dim a() = {95, 90, 98, 92, 96}
        selSortIt(a)
        printIt(a)

        Dim b() = {95, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87, 90, 98, 92, 96, 87}
        selSortIt(b)
        printIt(b)

        Dim c() = {95, 90}
        selSortIt(c)
        printIt(c)
    End Sub

    Sub sortIt(ByVal a)
        Dim i, j
        For j = 0 To a.length - 1 - 1
            For i = 0 To a.length - 1 - 1
                If a(i) > a(i + 1) Then
                    change(a(i), a(i + 1))
                End If
            Next
        Next
    End Sub

    Sub selSortIt(ByVal a)
        Dim i, j
        For j = 0 To a.length - 1 - 1
            For i = j + 1 To a.length - 1
                If a(j) > a(i) Then
                    change(a(j), a(i))
                End If
            Next
        Next
    End Sub

    Sub change(ByRef x, ByRef y)
        Dim t = x
        x = y
        y = t
    End Sub

    Sub printIt(ByVal a)
        Dim i
        Dim str1 = ""
        For i = 0 To a.length - 1
            str1 = str1 & a(i) & " "
        Next
        MsgBox(str1)
    End Sub
End Class

沒有留言:

張貼留言