vb.net - 有没有办法修复冒泡排序中的索引错误?
问题描述
我正在尝试在 vb 中编写冒泡排序,并且我的算法是正确的,但它总是说“索引超出了数组的范围。” 我不知道如何解决。我将把代码放在下面,任何帮助都会很好。
Sub Main()
Dim unsorted() As Integer = {17, 19, 12, 10, 15, 20}
Dim n As Integer = unsorted.Length
Dim swapped As Boolean = True
Dim temp
Dim list As String = ""
While n > 0 And swapped = True
For a = 0 To n - 1
If unsorted(a) > unsorted(a + 1) Then
temp = unsorted(a)
unsorted(a) = unsorted(a + 1)
unsorted(a + 1) = temp
swapped = True
End If
Next
End While
For Each number In unsorted
number &= list & " "
Next
Console.WriteLine(list)
Console.ReadLine()
End Sub
解决方案
我希望这段代码对你有用:
Private unsorted() As Byte = {17, 19, 12, 10, 15, 20}
Sub Main()
Dim temp As Byte
For pass = 1 To unsorted.Length - 1
For i = 0 To unsorted.Length - 2
If unsorted(i) > unsorted(i + 1) Then
temp = unsorted(i)
unsorted(i) = unsorted(i + 1)
unsorted(i + 1) = temp
End If
Next i
Next pass
Dim output As String = ""
For i = 0 To unsorted.Length - 1
output &= unsorted(i).ToString + vbNewLine
Next
Console.WriteLine(output)
Console.ReadKey()
End Sub
结果如下:
享受冒泡排序。
推荐阅读
- ios - UIDropInteractionDelegate performDrop 没有被调用?
- ruby-on-rails - 为什么 Puma 服务器不接受对代码的更改?
- sql - 不同结果的 SQL 计算
- dns - GitHub 页面 https/www 重定向
- c++ - 将 BYTE* 从 MODULEENTRY32 的 modBaseAddr 转换为 std::string
- c# - 网格甚至没有在 C# 中显示
- pgp - Keybase 私有 PGP 密钥导出失败,但解密按预期工作。那么我的私钥在哪里呢?
- windows - dir 命令意外行为
- javascript - Vue.js 与 Google Auth 使用模块?
- r - 计算某一行之前 14 行的一列的平均值,由每组的日期(年份)标识