【发布时间】:2018-04-13 19:55:14
【问题描述】:
我正在尝试编写一个包含两个部分的程序,具体取决于按下了两个按钮中的哪一个。
第一部分是正在工作的位,用户按下标有“unsort”的第一个按钮,这会触发一个循环,该循环显示一个输入框,要求输入随机数 8 次。这 8 个数字存储在一个数组中。
但是,这是我正在努力解决的第二部分;第二个按钮被标记为排序,应该输出用户刚刚使用第一个按钮输入的数字,从小到大。我知道这里必须使用冒泡排序,并且还必须使用循环中的循环,但是我不明白这些循环的内容。自从我的原始帖子以来,我已经编辑了帖子以在我之前坚持的循环中包含一些代码,但是它仍然没有产生所需的输出(所有数字按顺序排列)而是只是以看似随机的方式输出数字顺序
代码贴在下面,带有注释:
Public Class BubbleSort1
Dim Bubble(8) As Integer
Dim UnsortedList As String
Dim n As Integer
Dim SortedList As String
Dim temp As String
Private Sub btnUnsort_Click(sender As Object, e As EventArgs) Handles btnUnsort.Click
n = 8 ' number off values on array
For i = 1 To n ' when i is between 1 and size of array
Bubble(i) = InputBox("Enter Number") ' User inputs a number
UnsortedList = UnsortedList & " " & Bubble(i) & vbNewLine ' number is added to the unsorted list variable
Next i
lblUnsort.Text = UnsortedList ' outputs the array
End Sub
Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click
For i = 1 To n - 1 ' When i is between 1 and the array size - 1 (8-1):
For j = 1 To n - 1 ' Second loop - when j is between 1 and the array size - 1 (8-1):
If Bubble(j) > Bubble(j + 1) Then ' if bubble value j is greater than value j - 1:
temp = Bubble(j)
Bubble(j) = Bubble(j + 1) ' These lines are supost to order the numbers but aren'r currently doing so
Bubble(j + 1) = temp
SortedList = SortedList & Bubble(j) & vbNewLine ' Adding the number in order to a variable
End If
Next j
Next i
lblSort.Text = SortedList ' outputting the ordered numbers
End Sub
End Class
正如代码中所指出的,此代码中对数字进行排序的部分只是将它们按随机顺序排列,而不是实际对它们进行排序。
【问题讨论】:
-
这将为您提供学校项目所需的信息。 en.wikipedia.org/wiki/Bubble_sort你放一些代码后我会帮你的。
-
如果你有一杯红色的水(在上面贴上“Bubble(j)”的标签),一杯蓝色的水(在上面贴上“Bubble( j + 1)") 和一个标有“temp”的空玻璃杯,您将如何交换玻璃杯之间的有色水?
-
“明白这里必须使用冒泡排序”这是一个要求吗? .net 中已经内置了排序功能
-
@the_lotus 学校项目...老师想看看他们是否理解这个概念以及他们是否能够应用它
-
是的,这是任务的要求
标签: arrays vb.net loops bubble-sort