程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 選擇法排序 vb.net,法排序vb.net

選擇法排序 vb.net,法排序vb.net

編輯:關於.NET

選擇法排序 vb.net,法排序vb.net


Imports System.Threading

Module Module1

    Sub Main()

        'test code
        'Dim a, b As Integer
        'a = 3
        'b = 4
        'Exchange(a, b)
        'Console.WriteLine("a=" & a & ", b=" & b)

        Dim int_array(19) As Integer
        Dim maxValIndex As Integer
        Dim startIdx As Integer  '開始位置
        Dim rnd As New Random

        Console.WriteLine("原始數組:")
        '填充數組元素
        For i As Integer = 0 To int_array.Length - 1
            int_array(i) = rnd.Next(0, 500)
            Console.Write(int_array(i) & ", ")
            Thread.Sleep(150)
        Next

        '選擇法排序(降序)
        startIdx = 0 '默認從第一個元素開始比較
        Do
            maxValIndex = startIdx '默認第一個元素最大
            maxValIndex = GetMaxValIdx(int_array, maxValIndex, startIdx)  '求數組中最大值得下標

            If (maxValIndex <> startIdx) Then
                Exchange(int_array(maxValIndex), int_array(startIdx))
            End If
            startIdx += 1
        Loop While (startIdx < int_array.Length - 1)

        Console.WriteLine(vbCrLf & "排序之後:")
        For i As Integer = 0 To int_array.Length - 1
            Console.Write(int_array(i) & ", ")
        Next i

        Console.ReadKey()
    End Sub

    '求數組中最大值得下標,遞歸函數
    Public Function GetMaxValIdx(ByVal array() As Integer, ByVal maxValIdx As Integer, ByVal startIdx As Integer) As Integer
        For i As Integer = startIdx To array.Length - 1
            If (i <> maxValIdx) Then
                If array(i) > array(maxValIdx) Then
                    Return GetMaxValIdx(array, i, startIdx)
                End If
            End If
        Next

        Return maxValIdx
    End Function

    '交換值
    Public Sub Exchange(ByRef val1 As Integer, ByRef val2 As Integer)
        Dim temp As Integer
        temp = val1
        val1 = val2
        val2 = temp
    End Sub

End Module

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved