使用随机数和冒泡排序初始化数组

时间:2016-04-30 01:36:32

标签: vb.net

这是仅使用按钮2单击生成1个数字的代码。我需要它从数组中的按钮1中取出10个数字并生成从最小到最大排序的相同十个数字:

Public Class Form1
    Dim numberArray(9) As Integer
    Dim generator As New Random


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim min As Integer
        Dim r As Integer
        Dim max As Integer
        min = Val(TextBox1.Text)
        max = Val(TextBox2.Text)
        Label1.Text = ""
        For r = 0 To numberArray.GetUpperBound(0)
            numberArray(r) = generator.Next(min, max)
            Label1.Text += numberArray(r) & " "
            Label1.Text += ControlChars.NewLine
        Next

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


        Dim r As Integer
        Dim intTemp As Integer
        Dim blnExhchangeMade As Boolean
        blnExhchangeMade = False
        Do While blnExhchangeMade


            For r = LBound(numberArray) To (UBound(numberArray) - 1)
                If numberArray(r) < numberArray(r + 1) Then
                    intTemp = numberArray(r)
                    numberArray(r) = numberArray(r + 1)
                    numberArray(r + 1) = intTemp
                    blnExhchangeMade = True

                End If

            Next
        Loop
        Label2.Text += numberArray(r) & " "
        Label2.Text += ControlChars.NewLine
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

以下是我将要使用的代码:

Private Const elements As Integer = 9
Private numberArray(elements - 1) As Integer
Private generator As New Random

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim min As Integer = Integer.Parse(TextBox1.Text)
    Dim max As Integer = Integer.Parse(TextBox2.Text)
    Label1.Text = ""
    For r = 0 To elements - 1
        numberArray(r) = generator.Next(min, max + 1)
        Label1.Text += numberArray(r) & " "
        Label1.Text += System.Environment.NewLine
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim intTemp As Integer
    Dim blnExhchangeMade As Boolean = True
    Do While blnExhchangeMade
        blnExhchangeMade = False
        For r = 0 To elements - 2
            If numberArray(r) > numberArray(r + 1) Then
                intTemp = numberArray(r)
                numberArray(r) = numberArray(r + 1)
                numberArray(r + 1) = intTemp
                blnExhchangeMade = True
            End If
        Next
    Loop
    Label1.Text = ""
    For r = 0 To elements - 1
        Label1.Text += numberArray(r) & " "
        Label1.Text += System.Environment.NewLine
    Next
End Sub